package agent import ( "encoding/json" "errors" "fmt" "io" "net/http" "os" "strconv" "strings" "time" ) // DefaultGitHubAgentLogins are the GitHub identities whose activity watchpr // ignores when GITHUB_AGENT_LOGINS is unset. var DefaultGitHubAgentLogins = []string{"iuclabs-coder[bot]", "iuclabs-reviewer[bot]", "github-actions[bot]", "dependabot[bot]"} // GitHubAgentLogins returns GITHUB_AGENT_LOGINS (comma-separated) or the default. func GitHubAgentLogins() []string { var out []string for _, l := range strings.Split(os.Getenv("GITHUB_AGENT_LOGINS"), ",") { if l = strings.TrimSpace(l); l != "" { out = append(out, l) } } if len(out) == 0 { return DefaultGitHubAgentLogins } return out } // GitHubClient reads pull request state from the GitHub REST API. type GitHubClient struct { APIURL string HTTP *http.Client AgentLogins []string // Token returns the current token; nil means anonymous. Token func() (string, error) // Refresh mints a replacement when GitHub rejects the current token. Refresh func() (string, error) lastCI map[string]githubCI } // githubCI is the CI state last fetched for a PR's head. type githubCI struct { sha, state string } // maxRateLimitWait caps how long a watch pauses for one rate limit. const maxRateLimitWait = 15 * time.Minute // RateLimitError is a GitHub 403/429 rate limit, which clears at Reset. type RateLimitError struct { Path string Status int Reset time.Time } func (e *RateLimitError) Error() string { return fmt.Sprintf("github GET %s: rate limited (HTTP %d) until %s", e.Path, e.Status, e.Reset.Format(time.RFC3339)) } // rateLimitReset reads Retry-After (seconds), then X-RateLimit-Reset (epoch // seconds), falling back to a minute from now. func rateLimitReset(h http.Header, now time.Time) time.Time { if s, err := strconv.Atoi(h.Get("Retry-After")); err == nil { return now.Add(time.Duration(s) * time.Second) } if s, err := strconv.ParseInt(h.Get("X-RateLimit-Reset"), 10, 64); err == nil { return time.Unix(s, 0) } return now.Add(time.Minute) } // RateLimitWait reports whether err is a rate limit and how long from now to // wait it out, between a second and maxRateLimitWait. func RateLimitWait(err error, now time.Time) (time.Duration, bool) { var rl *RateLimitError if !errors.As(err, &rl) { return 0, false } return min(max(rl.Reset.Sub(now), time.Second), maxRateLimitWait), true } // NewGitHubClient builds an anonymous client for GITHUB_API_URL. func NewGitHubClient(agentLogins []string) (*GitHubClient, error) { apiURL, err := GitHubAPIURL() if err != nil { return nil, err } return &GitHubClient{APIURL: apiURL, HTTP: httpClient, AgentLogins: agentLogins}, nil } // UseApp authenticates the client as the app's installation. func (c *GitHubClient) UseApp(a *GitHubApp) { c.Token, c.Refresh = a.InstallationToken, a.RefreshInstallationToken } // do mirrors GiteaClient.do: a rejected token is re-minted once and the request // replayed; anonymous and permission failures are returned as they are. func (c *GitHubClient) do(path string, out any) error { token := "" if c.Token != nil { t, err := c.Token() if err != nil { return fmt.Errorf("github token: %w", err) } token = t } err := c.attempt(path, token, out) if !IsAuthError(err) { return err } if token == "" { return fmt.Errorf("%w: %w", ErrNoCredential, err) } if !IsCredentialRejected(err) || c.Refresh == nil { return err } token, refreshErr := c.Refresh() if refreshErr != nil { return fmt.Errorf("%w; re-minting token: %v", err, refreshErr) } if token == "" { return fmt.Errorf("%w; re-minting token yielded an empty token", err) } return c.attempt(path, token, out) } func (c *GitHubClient) attempt(path, token string, out any) error { req, err := http.NewRequest(http.MethodGet, c.APIURL+path, nil) if err != nil { return err } req.Header.Set("Accept", "application/vnd.github+json") req.Header.Set("X-GitHub-Api-Version", "2022-11-28") if token != "" { req.Header.Set("Authorization", "Bearer "+token) } resp, err := c.HTTP.Do(req) if err != nil { return err } defer func() { _ = resp.Body.Close() }() data, _ := io.ReadAll(resp.Body) body := strings.TrimSpace(string(data)) if resp.StatusCode < 200 || resp.StatusCode >= 300 { // A rate limit is a 403/429 that clears on its own, so it must not end a watch as an auth failure. if resp.StatusCode == http.StatusTooManyRequests || resp.Header.Get("X-RateLimit-Remaining") == "0" || (resp.StatusCode == http.StatusForbidden && strings.Contains(strings.ToLower(body), "rate limit")) { return &RateLimitError{Path: path, Status: resp.StatusCode, Reset: rateLimitReset(resp.Header, time.Now())} } return &APIError{Service: "github", Method: http.MethodGet, Path: path, StatusCode: resp.StatusCode, Body: body} } if err := json.Unmarshal(data, out); err != nil { return fmt.Errorf("github GET %s: decoding response: %w", path, err) } return nil } const githubPageSize = 100 // listAll fetches every page of a list endpoint. func listAll[T any](c *GitHubClient, path string) ([]T, error) { var all []T for page := 1; ; page++ { var items []T if err := c.do(path+"?per_page="+strconv.Itoa(githubPageSize)+"&page="+strconv.Itoa(page), &items); err != nil { return nil, err } all = append(all, items...) if len(items) < githubPageSize { return all, nil } } } type githubPR struct { State string `json:"state"` Title string `json:"title"` Merged bool `json:"merged"` Mergeable *bool `json:"mergeable"` MergeableState string `json:"mergeable_state"` HTMLURL string `json:"html_url"` Head struct { Sha string `json:"sha"` } `json:"head"` Base struct { Sha string `json:"sha"` } `json:"base"` } type githubCheckRun struct { Status string `json:"status"` Conclusion string `json:"conclusion"` } // githubActivity covers issue comments, review comments and reviews alike. type githubActivity struct { User struct { Login string `json:"login"` } `json:"user"` State string `json:"state"` } // githubMergeability maps GitHub's mergeable flag, which is null while GitHub // is still computing it. func githubMergeability(m *bool) Mergeability { switch { case m == nil: return MergeUnknown case *m: return MergeYes } return MergeNo } var failedCheckConclusions = map[string]bool{ "failure": true, "timed_out": true, "cancelled": true, "action_required": true, "startup_failure": true, } // mergeGitHubCI combines the commit-status state with the check runs: any // failure wins, then anything still running, then success. "" means no CI. func mergeGitHubCI(status string, statusCount int, runs []githubCheckRun) string { failed, pending, ok := false, false, false if statusCount > 0 { switch status { case "failure", "error": return status case "pending": pending = true case "success": ok = true } } for _, r := range runs { switch { case r.Status != "completed": pending = true case failedCheckConclusions[r.Conclusion]: failed = true default: ok = true } } switch { case failed: return "failure" case pending: return "pending" case ok: return "success" } return "" } // countNonAgentActivity counts items not authored by an agent login. Pending // reviews are drafts visible only to their author, so they never count. func countNonAgentActivity(items []githubActivity, agentLogins []string) int { n := 0 for _, it := range items { if it.State == "PENDING" { continue } isAgent := false for _, l := range agentLogins { if strings.EqualFold(it.User.Login, l) { isAgent = true break } } if !isAgent { n++ } } return n } // ciState fetches the merged CI state for sha; a 404 (head commit gone after a // merge) means no CI, as for Gitea. func (c *GitHubClient) ciState(repo, sha string) (string, error) { if sha == "" { return "", nil } var status struct { State string `json:"state"` TotalCount int `json:"total_count"` } if err := c.do("/repos/"+repo+"/commits/"+sha+"/status", &status); err != nil { if IsNotFound(err) { return "", nil } return "", err } // Only the first page of check runs is read; a head with more than 100 is not expected. var checks struct { CheckRuns []githubCheckRun `json:"check_runs"` } if err := c.do("/repos/"+repo+"/commits/"+sha+"/check-runs?per_page="+strconv.Itoa(githubPageSize), &checks); err != nil { if IsNotFound(err) { return "", nil } return "", err } return mergeGitHubCI(status.State, status.TotalCount, checks.CheckRuns), nil } // FetchState makes *GitHubClient a StateFetcher. The agent logins come from the // client, so the Gitea agentLogin argument is ignored. func (c *GitHubClient) FetchState(ref PRRef, _ string) (PRState, error) { repo := ref.RepoPath() n := strconv.Itoa(ref.Number) var pr githubPR if err := c.do("/repos/"+repo+"/pulls/"+n, &pr); err != nil { if IsNotFound(err) { return PRState{}, fmt.Errorf("%w: %w", errPRGone, err) } return PRState{}, err } // CI is re-read only while it can still change on its own: a new head, or a // state that is pending or not yet reported. ci, ok := c.lastCI[ref.String()] if !ok || ci.sha != pr.Head.Sha || ci.state == "pending" || ci.state == "" { state, err := c.ciState(repo, pr.Head.Sha) if err != nil { return PRState{}, err } ci = githubCI{sha: pr.Head.Sha, state: state} if c.lastCI == nil { c.lastCI = map[string]githubCI{} } c.lastCI[ref.String()] = ci } comments := 0 for _, path := range []string{"/issues/" + n + "/comments", "/pulls/" + n + "/comments", "/pulls/" + n + "/reviews"} { items, err := listAll[githubActivity](c, "/repos/"+repo+path) if err != nil { return PRState{}, err } comments += countNonAgentActivity(items, c.AgentLogins) } return PRState{ Ref: ref, State: pr.State, Merged: pr.Merged, HeadSHA: pr.Head.Sha, BaseSHA: pr.Base.Sha, Mergeable: githubMergeability(pr.Mergeable), MergeableState: pr.MergeableState, CIStatus: ci.state, NonAgentComments: comments, Title: pr.Title, URL: pr.HTMLURL, }, nil }