internal/store/statuses.go
183 lines · 5997 bytes
10 symbols in this file
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 return queryAll(s.DB, scanCommitStatus, `
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}
42
43// CommitStatusesFor is ListCommitStatuses for every commit on a list
44// page in one query, keyed by commit.
45func (s *Store) CommitStatusesFor(repoID int64, shas []string) (map[string][]CommitStatus, error) {
46 out := map[string][]CommitStatus{}
47 if len(shas) == 0 {
48 return out, nil
49 }
50 args := []any{repoID}
51 for _, sha := range shas {
52 args = append(args, sha)
53 }
54 rows, err := s.DB.Query(`
55 SELECT cs.commit_sha, cs.context, cs.state, cs.description, cs.target_url, COALESCE(u.username, ''), cs.updated_at
56 FROM commit_statuses cs LEFT JOIN users u ON u.id = cs.creator_id
57 WHERE cs.repo_id = ? AND cs.commit_sha IN (?`+strings.Repeat(",?", len(shas)-1)+`)
58 ORDER BY cs.context`, args...)
59 if err != nil {
60 return nil, err
61 }
62 defer rows.Close()
63 for rows.Next() {
64 var sha string
65 var c CommitStatus
66 if err := rows.Scan(&sha, &c.Context, &c.State, &c.Description, &c.TargetURL, &c.Creator, &c.UpdatedAt); err != nil {
67 return nil, err
68 }
69 out[sha] = append(out[sha], c)
70 }
71 return out, rows.Err()
72}
73
74// RepoHasStatuses reports whether anything has ever reported a status in
75// this repository. It is how require_checks tells a repository whose
76// checks come from outside — `status set`, with no .gitbay/ci.yml — from
77// one that has no checks at all.
78func (s *Store) RepoHasStatuses(repoID int64) (bool, error) {
79 var n int
80 err := s.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM commit_statuses WHERE repo_id = ?)`, repoID).Scan(&n)
81 return n == 1, err
82}
83
84// CombinedStatus reduces per-context states to one: error/failure dominate,
85// then pending, then success; "" when no statuses exist.
86// CombinedStatusFor returns the combined state for each of several commits
87// in one query. The log lists fifty commits at a time; asking per commit
88// turns one page into fifty round trips.
89func (s *Store) CombinedStatusFor(repoID int64, shas []string) (map[string]string, error) {
90 out := map[string]string{}
91 if len(shas) == 0 {
92 return out, nil
93 }
94 args := make([]any, 0, len(shas)+1)
95 args = append(args, repoID)
96 for _, sha := range shas {
97 args = append(args, sha)
98 }
99 q := `SELECT commit_sha, state FROM commit_statuses WHERE repo_id = ? AND commit_sha IN (?` +
100 strings.Repeat(",?", len(shas)-1) + `)`
101 rows, err := s.DB.Query(q, args...)
102 if err != nil {
103 return nil, err
104 }
105 defer rows.Close()
106 for rows.Next() {
107 var sha, state string
108 if err := rows.Scan(&sha, &state); err != nil {
109 return nil, err
110 }
111 // Same precedence as CombinedStatus, folded in as rows arrive.
112 switch {
113 case out[sha] == "failure":
114 case state == "error" || state == "failure":
115 out[sha] = "failure"
116 case state == "pending":
117 out[sha] = "pending"
118 case out[sha] == "":
119 out[sha] = "success"
120 }
121 }
122 return out, rows.Err()
123}
124
125func CombinedStatus(statuses []CommitStatus) string {
126 if len(statuses) == 0 {
127 return ""
128 }
129 combined := "success"
130 for _, s := range statuses {
131 switch s.State {
132 case "error", "failure":
133 return "failure"
134 case "pending":
135 combined = "pending"
136 }
137 }
138 return combined
139}
140
141// Check is a commit status paired with the build behind it. Only ci/<job>
142// statuses have one; anything posted through `status set` reports just the
143// state and when it last changed.
144type Check struct {
145 CommitStatus
146 Build int64 // build number, 0 when the check is not CI's
147 Duration time.Duration // 0 until that build has finished
148}
149
150// ChecksForCommit lists a commit's checks with their timing, and reduces
151// them to one combined state. Two queries at most, whatever the surface.
152func (s *Store) ChecksForCommit(repoID int64, sha string) ([]Check, string, error) {
153 statuses, err := s.ListCommitStatuses(repoID, sha)
154 if err != nil {
155 return nil, "", err
156 }
157 var builds map[string]Build
158 for _, st := range statuses {
159 if strings.HasPrefix(st.Context, "ci/") {
160 if builds, err = s.BuildsForCommit(repoID, sha); err != nil {
161 return nil, "", err
162 }
163 break
164 }
165 }
166 checks := make([]Check, 0, len(statuses))
167 for _, st := range statuses {
168 c := Check{CommitStatus: st}
169 if job, ok := strings.CutPrefix(st.Context, "ci/"); ok {
170 if b, ok := builds[job]; ok {
171 c.Build, c.Duration = b.Number, b.Elapsed()
172 }
173 }
174 checks = append(checks, c)
175 }
176 return checks, CombinedStatus(statuses), nil
177}
178
179func scanCommitStatus(row interface{ Scan(...any) error }) (CommitStatus, error) {
180 var c CommitStatus
181 err := row.Scan(&c.Context, &c.State, &c.Description, &c.TargetURL, &c.Creator, &c.UpdatedAt)
182 return c, err
183}