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