package main import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os/exec" "regexp" "sort" "strconv" "strings" "sync" "time" ) const ( githubPageLimit = 10 githubRequestLimit = 200 githubBodyLimit = 8 << 20 githubCacheLimit = 32 << 20 githubCacheEntries = 512 githubKnownScopeLimit = 128 githubKnownPullLimit = githubPendingLimit ) // Fetches serialize their scopes; individual requests share only briefly locked HTTP state. type GitHub struct { fetchGate chan struct{} mu sync.Mutex tokenMu sync.Mutex client *http.Client baseURL string token string resetAccount bool login string tokenProvider func(context.Context) (string, error) cache map[string]githubCached cacheBytes int cacheClock uint64 nextPoll time.Duration requests int known map[string]githubKnownScope rates map[string]githubRate blockedUntil time.Time now func() time.Time pollTimeout time.Duration requestTimeout time.Duration // ObserveRequest is optional and must be safe for concurrent worker calls. ObserveRequest func(GitHubRequestMetric) } type GitHubRequestMetric struct { Method string Path string Status int Duration time.Duration } type githubRate struct { remaining int64 reset time.Time } type githubKnownScope struct { pulls map[string]githubCandidate used time.Time discovered bool } type githubCached struct { body []byte header http.Header used uint64 } var ( githubBudgetExceeded = errors.New("GitHub request budget exhausted") githubForbidden = rpcError(-32024, "Forbidden", nil) ) type githubAPIError struct{ status int } func (e *githubAPIError) Error() string { return fmt.Sprintf("GitHub request failed (HTTP %d)", e.status) } func NewGitHub(ctx context.Context) (*GitHub, error) { g := &GitHub{ client: &http.Client{ Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, }, baseURL: "https://api.github.com", tokenProvider: githubToken, cache: make(map[string]githubCached), now: time.Now, } if err := g.refreshToken(ctx); err != nil { return nil, err } return g, nil } func githubToken(ctx context.Context) (string, error) { ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() cmd := exec.CommandContext(ctx, "gh", "auth", "token", "--hostname", "github.com") // Neither command diagnostics nor credentials may enter the MCP transport. cmd.Stderr = io.Discard b, err := cmd.Output() if err != nil { return "", errors.New("could not obtain GitHub credentials from gh") } token := strings.TrimSpace(string(b)) if token == "" { return "", errors.New("gh returned empty GitHub credentials") } return token, nil } func (g *GitHub) refreshToken(ctx context.Context) error { return g.refreshRejectedToken(ctx, "") } func (g *GitHub) refreshRejectedToken(ctx context.Context, rejected string) error { g.tokenMu.Lock() defer g.tokenMu.Unlock() g.mu.Lock() current := g.token g.mu.Unlock() if rejected != "" && current != rejected { return nil } if g.tokenProvider == nil { return errors.New("GitHub credentials cannot be refreshed") } token, err := g.tokenProvider(ctx) if err != nil || strings.TrimSpace(token) == "" { return errors.New("could not refresh GitHub credentials") } g.mu.Lock() defer g.mu.Unlock() if g.token != "" && g.token != strings.TrimSpace(token) { g.resetAccount = true } g.token = strings.TrimSpace(token) g.cache = make(map[string]githubCached) g.cacheBytes = 0 return nil } func (g *GitHub) Fetch(ctx context.Context, name string, args Arguments, since time.Time) (FetchResult, error) { return g.FetchPage(ctx, name, args, since, "") } func (g *GitHub) FetchPage(ctx context.Context, name string, args Arguments, since time.Time, continuation string) (FetchResult, error) { budget := g.pollTimeout if budget <= 0 { budget = 45 * time.Second } ctx, cancel := context.WithTimeout(ctx, budget) defer cancel() g.mu.Lock() if g.fetchGate == nil { g.fetchGate = make(chan struct{}, 1) } gate := g.fetchGate g.mu.Unlock() select { case gate <- struct{}{}: defer func() { <-gate }() case <-ctx.Done(): return FetchResult{}, ctx.Err() } if ctx.Err() != nil { return FetchResult{}, ctx.Err() } g.mu.Lock() if g.resetAccount { g.login = "" g.known = nil g.resetAccount = false } g.nextPoll, g.requests = 0, 0 wait := g.blockedUntil.Sub(g.now()) g.mu.Unlock() if wait > 0 { return FetchResult{NextPoll: wait}, errors.New("GitHub rate limit cooldown is active") } var result FetchResult var err error switch name { case activityName: if g.login == "" && len(args.Repos) == 0 && len(args.Authors) == 0 && args.Involves == "" { var user githubUser if _, err = g.get(ctx, "/user", &user); err == nil { if user.Login == "" { err = errors.New("GitHub returned no authenticated user") } else { g.login = user.Login } } } if err == nil { result, err = g.activityPage(ctx, args, since.UTC(), continuation) } case notificationsName: if continuation != "" { err = rpcError(-32602, "InvalidParams", nil) } else { result, err = g.notifications(ctx, since.UTC()) } default: err = errors.New("unsupported GitHub subscription") } g.mu.Lock() g.pace() if g.resetAccount { g.login, g.known, g.resetAccount = "", nil, false if name == activityName { err = errors.New("GitHub credentials changed; retry subscription") } } result.NextPoll = g.nextPoll g.mu.Unlock() if err != nil { result.Events = nil result.Complete = false } return result, err } func (g *GitHub) get(ctx context.Context, path string, out any) (http.Header, error) { return g.api(ctx, http.MethodGet, path, nil, out) } func (g *GitHub) api(ctx context.Context, method, path string, payload []byte, out any) (http.Header, error) { target, err := url.Parse(path) if err != nil { return nil, errors.New("invalid GitHub API URL") } base, err := url.Parse(g.baseURL) if err != nil { return nil, errors.New("invalid GitHub API base URL") } target = base.ResolveReference(target) // Pagination links are upstream data; never forward credentials to another origin. if target.Scheme != base.Scheme || target.Host != base.Host || target.User != nil { return nil, errors.New("GitHub pagination URL changed origin") } key := target.String() for attempt := 0; attempt < 2; attempt++ { g.mu.Lock() if wait := g.blockedUntil.Sub(g.now()); wait > 0 { g.hint(wait) g.mu.Unlock() return nil, errors.New("GitHub rate limit cooldown is active") } if g.requests >= githubRequestLimit { g.mu.Unlock() return nil, githubBudgetExceeded } g.requests++ token := g.token cached, hasCached := g.cache[key] if method != http.MethodGet { hasCached = false } g.mu.Unlock() timeout := g.requestTimeout if timeout <= 0 { timeout = 15 * time.Second } requestCtx, cancel := context.WithTimeout(ctx, timeout) header, retry, err := g.request(requestCtx, method, key, payload, token, cached, hasCached, out) cancel() if retry { if attempt == 1 || g.refreshRejectedToken(ctx, token) != nil { return nil, githubForbidden } continue } return header, err } return nil, githubForbidden } func (g *GitHub) request(ctx context.Context, method, key string, payload []byte, token string, cached githubCached, hasCached bool, out any) (http.Header, bool, error) { started, status := time.Now(), 0 defer func() { if g.ObserveRequest != nil { parsed, _ := url.Parse(key) g.ObserveRequest(GitHubRequestMetric{Method: method, Path: parsed.Path, Status: status, Duration: time.Since(started)}) } }() req, err := http.NewRequestWithContext(ctx, method, key, bytes.NewReader(payload)) if err != nil { return nil, false, errors.New("could not build GitHub request") } req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Accept", "application/vnd.github+json") req.Header.Set("X-GitHub-Api-Version", "2022-11-28") req.Header.Set("User-Agent", "github-events-mcp") if payload != nil { req.Header.Set("Content-Type", "application/json") } if hasCached { if etag := cached.header.Get("ETag"); etag != "" { req.Header.Set("If-None-Match", etag) } else if modified := cached.header.Get("Last-Modified"); modified != "" { req.Header.Set("If-Modified-Since", modified) } } response, err := g.client.Do(req) if err != nil { if ctx.Err() != nil { return nil, false, ctx.Err() } return nil, false, errors.New("GitHub request failed") } status = response.StatusCode g.mu.Lock() g.rateHints(response) g.mu.Unlock() if response.StatusCode == http.StatusUnauthorized { response.Body.Close() return nil, true, nil } if response.StatusCode == http.StatusNotModified { response.Body.Close() if !hasCached { return nil, false, errors.New("GitHub returned an uncached conditional response") } header := cached.header.Clone() for name, values := range response.Header { header[name] = values } g.mu.Lock() if g.token == token { g.store(key, cached.body, header) } g.pollHint(header) g.mu.Unlock() if err := json.Unmarshal(cached.body, out); err != nil { return nil, false, errors.New("invalid GitHub API response") } return header, false, nil } if response.StatusCode != http.StatusOK { // Read only to distinguish secondary limits from revoked access, never to report details. limited := response.Header.Get("Retry-After") != "" || response.Header.Get("X-RateLimit-Remaining") == "0" if response.StatusCode == http.StatusForbidden && !limited { body, _ := io.ReadAll(io.LimitReader(response.Body, 64<<10)) var diagnostic struct { Message string `json:"message"` } _ = json.Unmarshal(body, &diagnostic) message := strings.ToLower(diagnostic.Message) limited = strings.Contains(message, "rate limit") || strings.Contains(message, "abuse") if limited { g.mu.Lock() g.cooldown(time.Minute) g.mu.Unlock() } } response.Body.Close() if response.StatusCode == http.StatusUnauthorized || (response.StatusCode == http.StatusForbidden && !limited) { return nil, false, githubForbidden } return nil, false, &githubAPIError{status: response.StatusCode} } body, err := io.ReadAll(io.LimitReader(response.Body, githubBodyLimit+1)) response.Body.Close() if err != nil { return nil, false, errors.New("could not read GitHub API response") } if len(body) > githubBodyLimit { return nil, false, errors.New("GitHub API response exceeds size limit") } if err := json.Unmarshal(body, out); err != nil { return nil, false, errors.New("invalid GitHub API response") } if method == http.MethodGet { g.mu.Lock() if g.token == token { g.store(key, body, response.Header) } g.mu.Unlock() } return response.Header, false, nil } func (g *GitHub) hint(d time.Duration) { if d > g.nextPoll { g.nextPoll = d } } func (g *GitHub) pollHint(header http.Header) { if seconds, err := strconv.Atoi(header.Get("X-Poll-Interval")); err == nil && seconds > 0 { g.hint(time.Duration(seconds) * time.Second) } } func (g *GitHub) rateHints(response *http.Response) { g.pollHint(response.Header) remaining, remainingErr := strconv.ParseInt(response.Header.Get("X-RateLimit-Remaining"), 10, 64) reset, resetErr := strconv.ParseInt(response.Header.Get("X-RateLimit-Reset"), 10, 64) if remainingErr == nil && resetErr == nil && remaining >= 0 { if g.rates == nil { g.rates = make(map[string]githubRate) } resource := response.Header.Get("X-RateLimit-Resource") if resource == "" { resource = "core" } window := time.Unix(reset, 0) if prior, ok := g.rates[resource]; ok && prior.reset.Equal(window) && prior.remaining < remaining { remaining = prior.remaining } g.rates[resource] = githubRate{remaining: remaining, reset: window} } now := g.now() var retry time.Duration if value := response.Header.Get("Retry-After"); value != "" { if seconds, err := strconv.Atoi(value); err == nil { retry = time.Duration(seconds) * time.Second } else if date, err := http.ParseTime(value); err == nil { retry = date.Sub(now) } } if response.Header.Get("X-RateLimit-Remaining") == "0" { if seconds, err := strconv.ParseInt(response.Header.Get("X-RateLimit-Reset"), 10, 64); err == nil { if reset := time.Unix(seconds, 0).Sub(now) + time.Second; reset > retry { retry = reset } } } if response.StatusCode == http.StatusTooManyRequests && retry <= 0 { retry = time.Minute } if retry > 0 { g.cooldown(retry) } } // Spread a fetch's request cost across the remaining quota window instead of exhausting it hourly. func (g *GitHub) pace() { for _, rate := range g.rates { if remaining := rate.reset.Sub(g.now()); remaining > 0 && rate.remaining > 0 { g.hint(time.Duration(float64(remaining) * float64(g.requests) / float64(rate.remaining))) } } } func (g *GitHub) cooldown(delay time.Duration) { g.hint(delay) if until := g.now().Add(delay); until.After(g.blockedUntil) { g.blockedUntil = until } } func (g *GitHub) store(key string, body []byte, header http.Header) { if g.cache == nil { g.cache = make(map[string]githubCached) } if old, ok := g.cache[key]; ok { g.cacheBytes -= len(old.body) delete(g.cache, key) } for len(g.cache) >= githubCacheEntries || g.cacheBytes+len(body) > githubCacheLimit { oldest := "" var used uint64 = ^uint64(0) for key, entry := range g.cache { if entry.used < used { oldest, used = key, entry.used } } if oldest == "" { break } g.cacheBytes -= len(g.cache[oldest].body) delete(g.cache, oldest) } g.cacheClock++ g.cache[key] = githubCached{body: body, header: header.Clone(), used: g.cacheClock} g.cacheBytes += len(body) } func githubNext(header http.Header) string { for _, link := range strings.Split(header.Get("Link"), ",") { pieces := strings.Split(link, ";") if len(pieces) < 2 { continue } for _, parameter := range pieces[1:] { if strings.TrimSpace(parameter) == `rel="next"` { return strings.Trim(strings.TrimSpace(pieces[0]), "<>") } } } return "" } func (g *GitHub) pages(ctx context.Context, path string, visit func(json.RawMessage) error) (bool, error) { for page := 0; page < githubPageLimit; page++ { var entries []json.RawMessage header, err := g.get(ctx, path, &entries) if err != nil { return false, err } for _, entry := range entries { if err := visit(entry); err != nil { return false, err } } path = githubNext(header) if path == "" { return false, nil } } return true, nil } type githubUser struct { Login string `json:"login"` } type githubPull struct { Title string `json:"title"` URL string `json:"html_url"` State string `json:"state"` UpdatedAt time.Time `json:"updated_at"` User githubUser `json:"user"` RequestedReviewers []githubUser `json:"requested_reviewers"` rollup string MergedAt *time.Time `json:"merged_at"` Head struct { SHA string `json:"sha"` } `json:"head"` } type githubCandidate struct { repo string number int checksOnly bool reviewOnly bool remembered bool head string rollup string } func (c githubCandidate) key() string { return c.repo + "#" + strconv.Itoa(c.number) } // Remember open heads after a submitted review removes the pending-reviewer qualifier. // Scope and PR bounds are conservative: overflow is reported as an intentional gap. func (g *GitHub) remember(key string, pulls map[string]githubCandidate) bool { if len(pulls) > githubKnownPullLimit { return true } if g.known == nil { g.known = make(map[string]githubKnownScope) } for key, scope := range g.known { if g.now().Sub(scope.used) > 30*time.Minute { delete(g.known, key) } } if _, exists := g.known[key]; !exists && len(g.known) >= githubKnownScopeLimit { return true } scope := g.known[key] scope.pulls, scope.used = pulls, g.now() g.known[key] = scope return false } var githubRepoPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$`) var githubLoginPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_\[\]-]*$`) func (g *GitHub) queries(args Arguments, since time.Time) ([]string, error) { common := "is:pr updated:>=" + since.UTC().Format(time.RFC3339) if len(args.Pulls) > 0 && len(args.Repos) == 0 { // Search the pull requests' repositories; activityPage keeps only the listed ones. for _, pull := range args.Pulls { args.Repos = append(args.Repos, pull[:strings.IndexByte(pull, '#')]) } args.Repos = canonicalSet(args.Repos) } for _, repo := range args.Repos { if !githubRepoPattern.MatchString(repo) { return nil, errors.New("invalid GitHub repository filter") } } if args.Involves != "" { if !githubLoginPattern.MatchString(args.Involves) { return nil, errors.New("invalid GitHub involves filter") } common += " involves:" + args.Involves } scopes := []string{""} if len(args.Authors) > 0 { scopes = nil for _, author := range args.Authors { if !githubLoginPattern.MatchString(author) { return nil, errors.New("invalid GitHub author filter") } scopes = append(scopes, " author:"+author) } } else if len(args.Repos) == 0 && args.Involves == "" { if !githubLoginPattern.MatchString(g.login) { return nil, errors.New("invalid authenticated GitHub login") } // Remembered scoped PRs bridge a submitted review removing the request qualifier. // review-requested also matches requests to the user's teams, which are noisy. requested := " user-review-requested:" + g.login if args.Teams { requested = " review-requested:" + g.login } scopes = []string{" author:" + g.login, requested} if githubWanted(args)("review") { scopes = append(scopes, " reviewed-by:"+g.login) } } var queries []string for _, scope := range scopes { prefix := common + scope if len(prefix) > 256 { return nil, rpcError(-32025, "ResourceExhausted", map[string]any{"limit": "githubQueryLength", "max": 256}) } query := prefix for _, repo := range args.Repos { qualifier := " repo:" + repo if len(prefix+qualifier) > 256 { return nil, rpcError(-32025, "ResourceExhausted", map[string]any{"limit": "githubQueryLength", "max": 256}) } if len(query+qualifier) > 256 { queries = append(queries, query) query = prefix } query += qualifier } queries = append(queries, query) } return queries, nil } func (g *GitHub) search(ctx context.Context, queries []string) ([]githubCandidate, bool, error) { found := make(map[string]githubCandidate) truncated := false for _, query := range queries { path := "/search/issues?" + url.Values{"q": {query}, "sort": {"updated"}, "order": {"asc"}, "per_page": {"100"}}.Encode() seen := 0 for page := 0; page < githubPageLimit; page++ { var response struct { Total int `json:"total_count"` Incomplete bool `json:"incomplete_results"` Items []struct { Number int `json:"number"` RepositoryURL string `json:"repository_url"` PullRequest json.RawMessage `json:"pull_request"` } `json:"items"` } header, err := g.get(ctx, path, &response) if err != nil { return nil, false, err } seen += len(response.Items) if response.Incomplete { return nil, false, errors.New("GitHub search returned incomplete results") } truncated = truncated || response.Total > 1000 for _, item := range response.Items { if len(item.PullRequest) == 0 || bytes.Equal(item.PullRequest, []byte("null")) { continue } parsed, err := url.Parse(item.RepositoryURL) if err != nil { return nil, false, errors.New("invalid GitHub search repository") } repo := strings.TrimPrefix(parsed.Path, "/repos/") if !githubRepoPattern.MatchString(repo) || item.Number <= 0 { return nil, false, errors.New("invalid GitHub search pull request") } key := repo + "#" + strconv.Itoa(item.Number) candidate := githubCandidate{repo: repo, number: item.Number, reviewOnly: strings.Contains(query, " reviewed-by:")} if prior, exists := found[key]; !exists || prior.reviewOnly { found[key] = candidate } } path = githubNext(header) if path == "" { truncated = truncated || seen < response.Total break } if page == githubPageLimit-1 { truncated = true } } } pulls := make([]githubCandidate, 0, len(found)) for _, candidate := range found { pulls = append(pulls, candidate) } sort.Slice(pulls, func(i, j int) bool { if pulls[i].repo == pulls[j].repo { return pulls[i].number < pulls[j].number } return pulls[i].repo < pulls[j].repo }) return pulls, truncated, nil } type githubActivity struct { Repo string `json:"repo"` Number int `json:"number"` Title string `json:"title"` URL string `json:"url"` Kind string `json:"kind"` Actor string `json:"actor"` Summary string `json:"summary"` HeadSHA string `json:"headSha"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` } func githubSummary(s string) string { runes := []rune(strings.TrimSpace(s)) if len(runes) > 500 { runes = runes[:500] } return string(runes) } func (g *GitHub) activityPull(ctx context.Context, args Arguments, since, cutoff time.Time, candidate githubCandidate) (FetchResult, githubPull, error) { wanted := githubWanted(args) result := FetchResult{} prefix := "/repos/" + candidate.repo number := strconv.Itoa(candidate.number) var pull githubPull if _, err := g.get(ctx, prefix+"/pulls/"+number, &pull); err != nil { return FetchResult{}, pull, err } if candidate.reviewOnly { return g.recentOwnReviews(ctx, since, cutoff, candidate, pull) } defaultScope := len(args.Repos) == 0 && len(args.Authors) == 0 && args.Involves == "" inScope := !defaultScope || candidate.remembered || strings.EqualFold(pull.User.Login, g.login) for _, reviewer := range pull.RequestedReviewers { inScope = inScope || strings.EqualFold(reviewer.Login, g.login) } add := func(kind, id, actor, summary string, created, updated time.Time) { if !wanted(kind) || created.IsZero() || created.Before(since) || created.After(cutoff) { return } if updated.IsZero() { updated = created } data, _ := json.Marshal(githubActivity{ Repo: candidate.repo, Number: candidate.number, Title: githubSummary(pull.Title), URL: pull.URL, Kind: kind, Actor: actor, Summary: githubSummary(summary), HeadSHA: pull.Head.SHA, CreatedAt: created.UTC(), UpdatedAt: updated.UTC(), }) result.Events = append(result.Events, Event{ EventID: stableID(activityName, candidate.repo, number, kind, id), Name: activityName, Timestamp: created.UTC(), Data: data, }) } if githubNeedsTimeline(wanted) { clipped, err := g.pages(ctx, prefix+"/issues/"+number+"/timeline?per_page=100", func(raw json.RawMessage) error { var entry struct { ID json.Number `json:"id"` NodeID string `json:"node_id"` Event string `json:"event"` Body string `json:"body"` State string `json:"state"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` SubmittedAt time.Time `json:"submitted_at"` Actor githubUser `json:"actor"` User githubUser `json:"user"` RequestedReviewer githubUser `json:"requested_reviewer"` RequestedTeam struct { Slug string `json:"slug"` } `json:"requested_team"` } if err := json.Unmarshal(raw, &entry); err != nil { return errors.New("invalid GitHub timeline response") } kind, actor, summary := entry.Event, entry.Actor.Login, entry.Body created := entry.CreatedAt switch entry.Event { case "reviewed": if strings.EqualFold(entry.User.Login, g.login) && !entry.SubmittedAt.Before(since) && !entry.SubmittedAt.After(cutoff) { inScope = true } kind, actor, created = "review", entry.User.Login, entry.SubmittedAt summary = entry.State if entry.Body != "" { summary += ": " + entry.Body } case "commented": kind, actor = "comment", entry.User.Login case "review_requested": summary = entry.RequestedReviewer.Login if summary == "" { summary = entry.RequestedTeam.Slug } case "merged", "closed", "ready_for_review": summary = strings.ReplaceAll(entry.Event, "_", " ") if kind == "closed" && pull.MergedAt != nil && pull.MergedAt.Equal(created) { return nil } default: return nil } id := entry.ID.String() if id == "" { id = entry.NodeID } if id == "" { id = stableID(created.UTC().Format(time.RFC3339Nano), actor, summary) } add(kind, id, actor, summary, created, entry.UpdatedAt) return nil }) if err != nil { return FetchResult{}, pull, err } result.Truncated = result.Truncated || clipped } if wanted("review_comment") { clipped, err := g.pages(ctx, prefix+"/pulls/"+number+"/comments?per_page=100", func(raw json.RawMessage) error { var comment struct { ID json.Number `json:"id"` User githubUser `json:"user"` Body string `json:"body"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } if err := json.Unmarshal(raw, &comment); err != nil { return errors.New("invalid GitHub review comment response") } add("review_comment", comment.ID.String(), comment.User.Login, comment.Body, comment.CreatedAt, comment.UpdatedAt) return nil }) if err != nil { return FetchResult{}, pull, err } result.Truncated = result.Truncated || clipped } if wanted("check_suite") && pull.Head.SHA != "" { // Suites have updated_at, not completed_at; the latest completed one dates the rollup. path := prefix + "/commits/" + url.PathEscape(pull.Head.SHA) + "/check-suites?per_page=100" var finished time.Time for page := 0; page < githubPageLimit; page++ { var response struct { Suites []struct { ID json.Number `json:"id"` Status string `json:"status"` Conclusion string `json:"conclusion"` UpdatedAt time.Time `json:"updated_at"` App struct { Name string `json:"name"` Slug string `json:"slug"` } `json:"app"` } `json:"check_suites"` } header, err := g.get(ctx, path, &response) if err != nil { return FetchResult{}, pull, err } for _, suite := range response.Suites { if suite.Status != "completed" { pull.rollup = "PENDING" } else if pull.rollup != "PENDING" { if suite.Conclusion == "failure" || suite.Conclusion == "timed_out" || suite.Conclusion == "cancelled" || suite.Conclusion == "action_required" { pull.rollup = "FAILURE" } else if pull.rollup == "" { pull.rollup = "SUCCESS" } } if suite.Status == "completed" && suite.UpdatedAt.After(finished) { finished = suite.UpdatedAt } } path = githubNext(header) if path == "" { break } if page == githubPageLimit-1 { result.Truncated = true } } // One event per head once every suite has finished; a single suite finishing says nothing about CI. if githubRollupTerminal(pull.rollup) && !finished.Before(since) && !finished.After(cutoff) { data, _ := json.Marshal(githubActivity{ Repo: candidate.repo, Number: candidate.number, Title: githubSummary(pull.Title), URL: pull.URL, Kind: "check_suite", Actor: "github", Summary: "CI: " + strings.ToLower(pull.rollup), HeadSHA: pull.Head.SHA, CreatedAt: finished.UTC(), UpdatedAt: finished.UTC(), }) result.Events = append(result.Events, Event{ EventID: stableID(activityName, candidate.repo, number, "check_suite", pull.Head.SHA, pull.rollup), Name: activityName, Timestamp: finished.UTC(), Data: data, }) } } if !inScope { result.Events = nil pull.State = "" } result.Complete = true return result, pull, nil } func (g *GitHub) notifications(ctx context.Context, since time.Time) (FetchResult, error) { result := FetchResult{} path := "/notifications?" + url.Values{"all": {"true"}, "since": {since.UTC().Truncate(time.Hour).Format(time.RFC3339)}, "per_page": {"100"}}.Encode() truncated, err := g.pages(ctx, path, func(raw json.RawMessage) error { var notification struct { ID string `json:"id"` Reason string `json:"reason"` Unread bool `json:"unread"` UpdatedAt time.Time `json:"updated_at"` LastReadAt *time.Time `json:"last_read_at"` URL string `json:"url"` Subject struct { Title string `json:"title"` Type string `json:"type"` URL string `json:"url"` LatestCommentURL string `json:"latest_comment_url"` } `json:"subject"` Repository struct { FullName string `json:"full_name"` URL string `json:"html_url"` } `json:"repository"` } if err := json.Unmarshal(raw, ¬ification); err != nil { return errors.New("invalid GitHub notification response") } if notification.ID == "" || notification.UpdatedAt.IsZero() { return errors.New("GitHub notification lacks identity or timestamp") } if notification.UpdatedAt.Before(since) { return nil } if notification.LastReadAt != nil { *notification.LastReadAt = notification.LastReadAt.UTC() } data, _ := json.Marshal(map[string]any{ "id": notification.ID, "reason": notification.Reason, "unread": notification.Unread, "updatedAt": notification.UpdatedAt.UTC(), "lastReadAt": notification.LastReadAt, "url": notification.URL, "repo": notification.Repository.FullName, "repoUrl": notification.Repository.URL, "title": githubSummary(notification.Subject.Title), "subjectType": notification.Subject.Type, "subjectUrl": notification.Subject.URL, "latestCommentUrl": notification.Subject.LatestCommentURL, }) result.Events = append(result.Events, Event{ EventID: stableID(notificationsName, notification.ID, notification.UpdatedAt.UTC().Format(time.RFC3339Nano)), Name: notificationsName, Timestamp: notification.UpdatedAt.UTC(), Data: data, }) return nil }) result.Truncated, result.Complete = truncated, err == nil return result, err }