package main import ( "context" "encoding/json" "errors" "fmt" "net/http" "strconv" "strings" "time" ) type githubHeadObservation struct { result FetchResult pull githubPull err error } func githubRollupValid(state string) bool { switch state { case "", "PENDING", "EXPECTED", "SUCCESS", "FAILURE", "ERROR": return true } return false } func githubRollupTerminal(state string) bool { return state == "SUCCESS" || state == "FAILURE" || state == "ERROR" } func (g *GitHub) quietHeads(ctx context.Context, candidates []githubCandidate, checks bool, since time.Time) ([]githubHeadObservation, error) { if len(candidates) == 0 || len(candidates) > githubCIBatch { return nil, errors.New("invalid GitHub CI batch") } var query strings.Builder query.WriteString("query {") for i, candidate := range candidates { parts := strings.Split(candidate.repo, "/") if len(parts) != 2 || !githubRepoPattern.MatchString(candidate.repo) || candidate.number <= 0 { return nil, errors.New("invalid GitHub CI candidate") } fmt.Fprintf(&query, " p%d: repository(owner:%s,name:%s) { pullRequest(number:%d) { title url state updatedAt headRefOid", i, strconv.Quote(parts[0]), strconv.Quote(parts[1]), candidate.number) if checks { query.WriteString(" commits(last:1) { nodes { commit { statusCheckRollup { state } } } }") } query.WriteString(" } }") } query.WriteString(" }") payload, _ := json.Marshal(map[string]string{"query": query.String()}) var response struct { Data map[string]json.RawMessage `json:"data"` Errors []struct { Type string `json:"type"` Path []json.RawMessage `json:"path"` } `json:"errors"` } if _, err := g.api(ctx, http.MethodPost, "/graphql", payload, &response); err != nil { return nil, err } aliasErrors := make(map[string]error) for _, entry := range response.Errors { if len(entry.Path) == 0 { return nil, errors.New("GitHub CI query failed") } var alias string if json.Unmarshal(entry.Path[0], &alias) != nil { return nil, errors.New("GitHub CI query failed") } switch entry.Type { case "NOT_FOUND": aliasErrors[alias] = &githubAPIError{status: 404} case "FORBIDDEN": aliasErrors[alias] = githubForbidden default: aliasErrors[alias] = errors.New("GitHub CI query failed") } } observed := g.now().UTC() observations := make([]githubHeadObservation, len(candidates)) for i, candidate := range candidates { alias := fmt.Sprintf("p%d", i) o := &observations[i] if err := aliasErrors[alias]; err != nil { o.err = err continue } raw, exists := response.Data[alias] if !exists { return nil, errors.New("GitHub CI query omitted a pull request") } var repository struct { Pull *struct { Title string `json:"title"` URL string `json:"url"` State string `json:"state"` UpdatedAt time.Time `json:"updatedAt"` Head string `json:"headRefOid"` Commits struct { Nodes []struct { Commit struct { Rollup *struct { State string `json:"state"` } `json:"statusCheckRollup"` } `json:"commit"` } `json:"nodes"` } `json:"commits"` } `json:"pullRequest"` } if json.Unmarshal(raw, &repository) != nil { return nil, errors.New("invalid GitHub CI response") } if repository.Pull == nil { o.err = &githubAPIError{status: 404} continue } pull := repository.Pull o.pull.Title, o.pull.URL, o.pull.State = pull.Title, pull.URL, strings.ToLower(pull.State) o.pull.UpdatedAt, o.pull.Head.SHA = pull.UpdatedAt, pull.Head if checks && len(pull.Commits.Nodes) > 0 && pull.Commits.Nodes[0].Commit.Rollup != nil { o.pull.rollup = pull.Commits.Nodes[0].Commit.Rollup.State if !githubRollupValid(o.pull.rollup) { return nil, errors.New("invalid GitHub CI state") } } o.result.Complete = true // Unknown heads establish a baseline; a push itself is not a CI completion. if !checks || candidate.head == "" || candidate.head != pull.Head || candidate.rollup == o.pull.rollup || !githubRollupTerminal(o.pull.rollup) || observed.Before(since) { continue } 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(o.pull.rollup), HeadSHA: pull.Head, CreatedAt: observed, UpdatedAt: observed, }) o.result.Events = []Event{{ EventID: stableID(activityName, candidate.repo, strconv.Itoa(candidate.number), "check_suite", pull.Head, o.pull.rollup), Name: activityName, Timestamp: observed, Data: data, }} } return observations, nil }