internal/store/statuses.go

v1.22.0
gitbay/internal/store/statuses.go history · blame · raw

149 lines · 4598 bytes

  1package store
  2
  3import (
  4	"strings"
  5	"time"
  6)
  7
  8type CommitStatus struct {
  9	Context     string
 10	State       string // pending | success | failure | error | skipped
 11	Description string
 12	TargetURL   string
 13	Creator     string
 14	UpdatedAt   string
 15}
 16
 17// SetCommitStatus upserts the latest state for one context on one commit.
 18// A zero creatorID records no creator (system actions like the scheduler).
 19func (s *Store) SetCommitStatus(repoID int64, sha, context, state, description, targetURL string, creatorID int64) error {
 20	var creator any
 21	if creatorID != 0 {
 22		creator = creatorID
 23	}
 24	_, err := s.DB.Exec(`
 25		INSERT INTO commit_statuses (repo_id, commit_sha, context, state, description, target_url, creator_id)
 26		VALUES (?, ?, ?, ?, ?, ?, ?)
 27		ON CONFLICT (repo_id, commit_sha, context) DO UPDATE SET
 28			state = excluded.state, description = excluded.description,
 29			target_url = excluded.target_url, creator_id = excluded.creator_id,
 30			updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')`,
 31		repoID, sha, context, state, description, targetURL, creator)
 32	return err
 33}
 34
 35// ListCommitStatuses returns the latest status per context for a commit.
 36func (s *Store) ListCommitStatuses(repoID int64, sha string) ([]CommitStatus, error) {
 37	rows, err := s.DB.Query(`
 38		SELECT cs.context, cs.state, cs.description, cs.target_url, COALESCE(u.username, ''), cs.updated_at
 39		FROM commit_statuses cs LEFT JOIN users u ON u.id = cs.creator_id
 40		WHERE cs.repo_id = ? AND cs.commit_sha = ? ORDER BY cs.context`, repoID, sha)
 41	if err != nil {
 42		return nil, err
 43	}
 44	defer rows.Close()
 45	var out []CommitStatus
 46	for rows.Next() {
 47		var c CommitStatus
 48		if err := rows.Scan(&c.Context, &c.State, &c.Description, &c.TargetURL, &c.Creator, &c.UpdatedAt); err != nil {
 49			return nil, err
 50		}
 51		out = append(out, c)
 52	}
 53	return out, rows.Err()
 54}
 55
 56// CombinedStatus reduces per-context states to one: error/failure dominate,
 57// then pending, then success; "" when no statuses exist.
 58// CombinedStatusFor returns the combined state for each of several commits
 59// in one query. The log lists fifty commits at a time; asking per commit
 60// turns one page into fifty round trips.
 61func (s *Store) CombinedStatusFor(repoID int64, shas []string) (map[string]string, error) {
 62	out := map[string]string{}
 63	if len(shas) == 0 {
 64		return out, nil
 65	}
 66	args := make([]any, 0, len(shas)+1)
 67	args = append(args, repoID)
 68	for _, sha := range shas {
 69		args = append(args, sha)
 70	}
 71	q := `SELECT commit_sha, state FROM commit_statuses WHERE repo_id = ? AND commit_sha IN (?` +
 72		strings.Repeat(",?", len(shas)-1) + `)`
 73	rows, err := s.DB.Query(q, args...)
 74	if err != nil {
 75		return nil, err
 76	}
 77	defer rows.Close()
 78	for rows.Next() {
 79		var sha, state string
 80		if err := rows.Scan(&sha, &state); err != nil {
 81			return nil, err
 82		}
 83		// Same precedence as CombinedStatus, folded in as rows arrive.
 84		switch {
 85		case out[sha] == "failure":
 86		case state == "error" || state == "failure":
 87			out[sha] = "failure"
 88		case state == "pending":
 89			out[sha] = "pending"
 90		case out[sha] == "":
 91			out[sha] = "success"
 92		}
 93	}
 94	return out, rows.Err()
 95}
 96
 97func CombinedStatus(statuses []CommitStatus) string {
 98	if len(statuses) == 0 {
 99		return ""
100	}
101	combined := "success"
102	for _, s := range statuses {
103		switch s.State {
104		case "error", "failure":
105			return "failure"
106		case "pending":
107			combined = "pending"
108		}
109	}
110	return combined
111}
112
113// Check is a commit status paired with the build behind it. Only ci/<job>
114// statuses have one; anything posted through `status set` reports just the
115// state and when it last changed.
116type Check struct {
117	CommitStatus
118	Build    int64         // build number, 0 when the check is not CI's
119	Duration time.Duration // 0 until that build has finished
120}
121
122// ChecksForCommit lists a commit's checks with their timing, and reduces
123// them to one combined state. Two queries at most, whatever the surface.
124func (s *Store) ChecksForCommit(repoID int64, sha string) ([]Check, string, error) {
125	statuses, err := s.ListCommitStatuses(repoID, sha)
126	if err != nil {
127		return nil, "", err
128	}
129	var builds map[string]Build
130	for _, st := range statuses {
131		if strings.HasPrefix(st.Context, "ci/") {
132			if builds, err = s.BuildsForCommit(repoID, sha); err != nil {
133				return nil, "", err
134			}
135			break
136		}
137	}
138	checks := make([]Check, 0, len(statuses))
139	for _, st := range statuses {
140		c := Check{CommitStatus: st}
141		if job, ok := strings.CutPrefix(st.Context, "ci/"); ok {
142			if b, ok := builds[job]; ok {
143				c.Build, c.Duration = b.Number, b.Elapsed()
144			}
145		}
146		checks = append(checks, c)
147	}
148	return checks, CombinedStatus(statuses), nil
149}