package main import ( "bytes" "context" "encoding/base64" "encoding/json" "errors" "io" "slices" "sort" "strings" "sync" "time" ) const ( githubPullBatch = 16 githubWorkers = 4 githubPendingLimit = 1000 githubContinuationLimit = 100 << 10 githubCIBatch = 100 ) type githubPending struct { Repo string `json:"r"` Number int `json:"n"` ChecksOnly bool `json:"c,omitempty"` ReviewOnly bool `json:"b,omitempty"` Remembered bool `json:"m,omitempty"` Head string `json:"h,omitempty"` Rollup string `json:"s,omitempty"` } type githubContinuation struct { Version int `json:"v"` Scope string `json:"s"` Since time.Time `json:"since"` Cutoff time.Time `json:"to"` Truncated bool `json:"gap,omitempty"` Pending []githubPending `json:"p"` } func githubCanonicalArgs(args Arguments) Arguments { lists := []*[]string{&args.Repos, &args.Authors, &args.Pulls, &args.Kinds} for i, list := range lists { values := append([]string(nil), (*list)...) if i < 3 { for j := range values { values[j] = strings.ToLower(values[j]) } } *list = canonicalSet(values) } args.Involves = strings.ToLower(args.Involves) return args } func githubWanted(args Arguments) func(string) bool { kinds := make(map[string]bool, len(args.Kinds)) for _, kind := range args.Kinds { kinds[kind] = true } return func(kind string) bool { return len(kinds) == 0 || kinds[kind] } } func githubNeedsTimeline(wanted func(string) bool) bool { for _, kind := range []string{"review", "comment", "merged", "closed", "ready_for_review", "review_requested"} { if wanted(kind) { return true } } return false } func githubResume(encoded, key string, since, now time.Time) (githubContinuation, error) { var c githubContinuation invalid := rpcError(-32602, "InvalidParams", nil) if len(encoded) > githubContinuationLimit { return c, invalid } raw, err := base64.RawURLEncoding.DecodeString(encoded) if err != nil { return c, invalid } d := json.NewDecoder(bytes.NewReader(raw)) d.DisallowUnknownFields() if d.Decode(&c) != nil || d.Decode(new(any)) != io.EOF { return c, invalid } if c.Version != 1 || c.Scope != key || c.Since.After(since) || c.Since.Before(now.Add(-replayWindow-indexOverlap)) || c.Cutoff.IsZero() || c.Cutoff.Before(c.Since) || c.Cutoff.After(now) || len(c.Pending) == 0 || len(c.Pending) > githubPendingLimit { return c, invalid } seen := make(map[string]bool, len(c.Pending)) for _, p := range c.Pending { if !githubRepoPattern.MatchString(p.Repo) || len(p.Repo) > 200 || p.Number <= 0 || p.Number > 2147483647 || len(p.Head) > 128 || !githubRollupValid(p.Rollup) || (p.ChecksOnly && (!p.Remembered || p.ReviewOnly)) { return c, invalid } key := githubCandidate{repo: p.Repo, number: p.Number}.key() if seen[key] { return c, invalid } seen[key] = true } return c, nil } func githubPause(c githubContinuation) (string, error) { raw, err := json.Marshal(c) if err != nil { return "", errors.New("could not encode GitHub continuation") } encoded := base64.RawURLEncoding.EncodeToString(raw) if len(encoded) > githubContinuationLimit { return "", errors.New("GitHub continuation exceeds size limit") } return encoded, nil } func pendingGitHub(c githubCandidate) githubPending { return githubPending{Repo: c.repo, Number: c.number, ChecksOnly: c.checksOnly, ReviewOnly: c.reviewOnly, Remembered: c.remembered, Head: c.head, Rollup: c.rollup} } func (p githubPending) candidate() githubCandidate { return githubCandidate{repo: p.Repo, number: p.Number, checksOnly: p.ChecksOnly, reviewOnly: p.ReviewOnly, remembered: p.Remembered, head: p.Head, rollup: p.Rollup} } func (g *GitHub) activityPage(ctx context.Context, args Arguments, since time.Time, continuation string) (FetchResult, error) { args = githubCanonicalArgs(args) key := subscriptionKey(activityName, args) wanted := githubWanted(args) needsDeep := githubNeedsTimeline(wanted) || wanted("review_comment") var c githubContinuation bootstrapped := false if continuation != "" { var err error c, err = githubResume(continuation, key, since, g.now()) if err != nil { return FetchResult{}, err } if _, exists := g.known[key]; !exists && !g.remember(key, make(map[string]githubCandidate)) { scope := g.known[key] // A restarted source must bootstrap its missing live CI cache on the next new range. scope.discovered = false g.known[key] = scope } } else { c = githubContinuation{Version: 1, Scope: key, Since: since, Cutoff: g.now().UTC()} queries, err := g.queries(args, since) if err != nil { return FetchResult{}, err } candidates, clipped, err := g.search(ctx, queries) if err != nil { return FetchResult{}, err } c.Truncated = clipped found := make(map[string]githubCandidate, len(candidates)) for _, candidate := range candidates { found[candidate.key()] = candidate } scope := g.known[key] if g.now().Sub(scope.used) > 30*time.Minute { scope = githubKnownScope{} } for k, candidate := range found { if prior, ok := scope.pulls[k]; ok { candidate.head, candidate.rollup, candidate.remembered = prior.head, prior.rollup, true candidate.reviewOnly = false found[k] = candidate } } if wanted("check_suite") && !scope.discovered { // Bootstrap quiet open heads once per live scope. Their timelines are never scanned. qualifier := "updated:>=" + since.UTC().Format(time.RFC3339) var openQueries []string for _, query := range queries { if !strings.Contains(query, " reviewed-by:") { openQueries = append(openQueries, strings.Replace(query, qualifier, "is:open", 1)) } } open, clipped, err := g.search(ctx, openQueries) if err != nil { return FetchResult{}, err } c.Truncated = c.Truncated || clipped for _, candidate := range open { if prior, exists := found[candidate.key()]; !exists || prior.reviewOnly { candidate.checksOnly, candidate.remembered = true, true found[candidate.key()] = candidate } } scope.discovered = true bootstrapped = true } if g.now().Sub(scope.used) <= 30*time.Minute { for k, candidate := range scope.pulls { if _, exists := found[k]; !exists { candidate.checksOnly, candidate.remembered = true, true found[k] = candidate } } } if len(args.Pulls) > 0 { for k := range found { if !slices.Contains(args.Pulls, strings.ToLower(k)) { delete(found, k) } } } if scope.pulls == nil { scope.pulls = make(map[string]githubCandidate) } if g.remember(key, scope.pulls) { c.Truncated = true } else { scope.used = g.now() g.known[key] = scope } keys := make([]string, 0, len(found)) for k := range found { keys = append(keys, k) } sort.Strings(keys) if len(keys) > githubPendingLimit { keys = keys[:githubPendingLimit] c.Truncated = true } for _, k := range keys { c.Pending = append(c.Pending, pendingGitHub(found[k])) } c, err = githubBoundPending(c) if err != nil { return FetchResult{}, err } } replay := "" if len(c.Pending) > 0 { var err error replay, err = githubPause(c) if err != nil { return FetchResult{}, err } } type outcome struct { index int result FetchResult pull githubPull err error } var deep, quiet []int for i, pending := range c.Pending { if pending.ChecksOnly { if len(quiet) < githubCIBatch { quiet = append(quiet, i) } } else if len(deep) < githubPullBatch { deep = append(deep, i) } } completed := make(map[int]bool) result := FetchResult{Complete: true, Truncated: c.Truncated, CheckedTo: c.Cutoff, Replay: replay} var firstErr error accessible, forbidden := 0, 0 apply := func(o outcome) { candidate := c.Pending[o.index].candidate() var api *githubAPIError missing := errors.As(o.err, &api) && api.status == 404 lostAccess := candidate.remembered && errors.Is(o.err, githubForbidden) if o.err != nil && !missing && !lostAccess { if firstErr == nil { firstErr = o.err } return } completed[o.index] = true if missing || lostAccess { result.Truncated = true if lostAccess { forbidden++ } } else { accessible++ result.Events = append(result.Events, o.result.Events...) result.Truncated = result.Truncated || o.result.Truncated } if scope, ok := g.known[key]; ok { delete(scope.pulls, candidate.key()) // Metadata may be newer than the checked window. Keep a short-lived bridge // until its closure/merge event can be consumed by a later snapshot. if o.err == nil && !candidate.reviewOnly && (o.pull.State == "open" || o.pull.UpdatedAt.After(c.Cutoff)) { candidate.head, candidate.rollup = o.pull.Head.SHA, o.pull.rollup candidate.remembered = true if len(scope.pulls) < githubKnownPullLimit { scope.pulls[candidate.key()] = candidate } else { result.Truncated = true } } scope.used = g.now() g.known[key] = scope } } work := make(chan int, len(deep)) finished := make(chan outcome, len(deep)) for _, i := range deep { work <- i } close(work) var workers sync.WaitGroup for worker := 0; worker < githubWorkers; worker++ { workers.Add(1) go func() { defer workers.Done() for i := range work { page, pull, err := g.activityPull(ctx, args, since, c.Cutoff, c.Pending[i].candidate()) finished <- outcome{index: i, result: page, pull: pull, err: err} } }() } workers.Wait() close(finished) for o := range finished { apply(o) } if len(quiet) > 0 { candidates := make([]githubCandidate, len(quiet)) for i, index := range quiet { candidates[i] = c.Pending[index].candidate() } observations, err := g.quietHeads(ctx, candidates, wanted("check_suite"), since) if err != nil { if firstErr == nil { firstErr = err } } else { for i, observation := range observations { index := quiet[i] // A remembered PR changing after the reviewer qualifier vanished stays in scope. changed := !observation.pull.UpdatedAt.Before(since) known := c.Pending[index].Head != "" if observation.err == nil && changed && known && needsDeep { // Schedule deep work on the next page rather than scanning up to 100 timelines here. c.Pending[index].ChecksOnly = false } else { apply(outcome{index: index, result: observation.result, pull: observation.pull, err: observation.err}) } } } } resetDiscovery := func() { if bootstrapped { if scope, exists := g.known[key]; exists { scope.discovered = false g.known[key] = scope } } } if accessible == 0 && forbidden > 0 { resetDiscovery() return FetchResult{}, githubForbidden } remaining := make([]githubPending, 0, len(c.Pending)-len(completed)) for i, pending := range c.Pending { if !completed[i] { remaining = append(remaining, pending) } } if len(remaining) > 0 { if len(completed) == 0 && firstErr != nil { resetDiscovery() return FetchResult{}, firstErr } c.Pending, c.Truncated = remaining, result.Truncated encoded, err := githubPause(c) if err != nil { return FetchResult{}, err } result.Continuation = encoded } sort.Slice(result.Events, func(i, j int) bool { if result.Events[i].Timestamp.Equal(result.Events[j].Timestamp) { return result.Events[i].EventID < result.Events[j].EventID } return result.Events[i].Timestamp.Before(result.Events[j].Timestamp) }) return result, nil } // Fit the serialized descriptor, not just its PR count: long repository names // and prior head baselines consume the same portable continuation byte budget. func githubBoundPending(c githubContinuation) (githubContinuation, error) { if _, err := githubPause(c); err == nil { return c, nil } c.Truncated = true low, high := 0, len(c.Pending) for low < high { mid := low + (high-low+1)/2 trial := c trial.Pending = c.Pending[:mid] if _, err := githubPause(trial); err == nil { low = mid } else { high = mid - 1 } } if low == 0 { return c, errors.New("GitHub continuation cannot fit a pull request") } c.Pending = c.Pending[:low] return c, nil }