Commit 3d3b1e202d

3d3b1e202dc412a2d0f69f7e6b5e0c62d9cde1c1

parent: 93d98753bc

Verified · cmc ci/build: success ci/quality: success ci/test: success

cmc <hello@cleberg.net> · 2026-10-23 05:46 UTC

store: queryAll and execAll; split compound conditions

- queryAll reads every row with a scan function; the store's list
  queries, feed events and due mail/pushes/deliveries use it.
- feedSelect and scanFeedEvent for the three activity feeds; dayCounts
  for the user and org activity graphs.
- execAll for SetMRTarget and RemoveSnippetFile.
- Long boolean conditions split into guards or named helpers
  (bareAddress, isDigit); isForbidden and IsInternal list their cases.

Layout: unified · split

internal/config/config.go +11 −2
@@ -463,8 +463,7 @@ func (m MailInbound) validate() []error {
463 errs = append(errs, fmt.Errorf("mail.inbound.trusted_authserv_id %q must be a bare host name such as mx.google.com", id)) 463 errs = append(errs, fmt.Errorf("mail.inbound.trusted_authserv_id %q must be a bare host name such as mx.google.com", id))
464 } 464 }
465 if a := m.ReplyAddress; a != "" { 465 if a := m.ReplyAddress; a != "" {
466 local, domain, ok := strings.Cut(a, "@") 466 if !bareAddress(a) {
467 if !ok || local == "" || domain == "" || strings.ContainsAny(a, "+ <>\"\r\n") || strings.Contains(domain, "@") {
468 errs = append(errs, fmt.Errorf("mail.inbound.reply_address %q must be a bare address such as reply@example.org, with no + in it", a)) 467 errs = append(errs, fmt.Errorf("mail.inbound.reply_address %q must be a bare address such as reply@example.org, with no + in it", a))
469 } 468 }
470 } 469 }
@@ -855,3 +854,13 @@ func (h HTTP) TrustedProxyNets() ([]*net.IPNet, error) {
855 } 854 }
856 return nets, nil 855 return nets, nil
857} 856}
857
858// bareAddress reports whether a is local@domain and nothing else: no +,
859// spaces, angle brackets, quotes or line breaks.
860func bareAddress(a string) bool {
861 local, domain, ok := strings.Cut(a, "@")
862 if !ok || local == "" || domain == "" {
863 return false
864 }
865 return !strings.ContainsAny(a, "+ <>\"\r\n") && !strings.Contains(domain, "@")
866}
internal/control/help.go +4 −2
@@ -232,8 +232,10 @@ func (c *Ctx) shownAs(registered, full string) string {
232// other command's name, so it keeps its registered path. 232// other command's name, so it keeps its registered path.
233func (c *Ctx) shownBelow(registered, other string) string { 233func (c *Ctx) shownBelow(registered, other string) string {
234 reg, cli, o := strings.Fields(registered), strings.Fields(c.CLIPath), strings.Fields(other) 234 reg, cli, o := strings.Fields(registered), strings.Fields(c.CLIPath), strings.Fields(other)
235 if len(cli) == 0 || len(reg) == 0 || len(o) < len(reg) || cli[len(cli)-1] != reg[len(reg)-1] || 235 if len(cli) == 0 || len(reg) == 0 || len(o) < len(reg) {
236 !slices.Equal(o[:len(reg)-1], reg[:len(reg)-1]) { 236 return other
237 }
238 if cli[len(cli)-1] != reg[len(reg)-1] || !slices.Equal(o[:len(reg)-1], reg[:len(reg)-1]) {
237 return other 239 return other
238 } 240 }
239 return joinPath(append(slices.Clip(cli[:len(cli)-1]), o[len(reg)-1:]...)) 241 return joinPath(append(slices.Clip(cli[:len(cli)-1]), o[len(reg)-1:]...))
internal/control/term.go +4 −2
@@ -326,8 +326,10 @@ func (t Term) paintDiffLine(l string) string {
326// "1: abc1234 = 1: def5678 subject", either side possibly "-: -------". 326// "1: abc1234 = 1: def5678 subject", either side possibly "-: -------".
327func rangePair(l string) bool { 327func rangePair(l string) bool {
328 f := strings.Fields(l) 328 f := strings.Fields(l)
329 return len(f) >= 5 && strings.HasSuffix(f[0], ":") && strings.HasSuffix(f[3], ":") && 329 if len(f) < 5 || len(f[2]) != 1 {
330 strings.ContainsAny(f[2], "=!<>") && len(f[2]) == 1 330 return false
331 }
332 return strings.HasSuffix(f[0], ":") && strings.HasSuffix(f[3], ":") && strings.ContainsAny(f[2], "=!<>")
331} 333}
332 334
333// toolSGR matches the colour sequences build tools print. 335// toolSGR matches the colour sequences build tools print.
internal/deps/version.go +4 −2
@@ -49,7 +49,7 @@ func split(v string) ([]int, string) {
49 i := 0 49 i := 0
50 for i < len(v) { 50 for i < len(v) {
51 j := i 51 j := i
52 for j < len(v) && v[j] >= '0' && v[j] <= '9' { 52 for j < len(v) && isDigit(v[j]) {
53 j++ 53 j++
54 } 54 }
55 if j == i { 55 if j == i {
@@ -60,7 +60,7 @@ func split(v string) ([]int, string) {
60 break 60 break
61 } 61 }
62 nums = append(nums, n) 62 nums = append(nums, n)
63 if j < len(v) && v[j] == '.' && j+1 < len(v) && v[j+1] >= '0' && v[j+1] <= '9' { 63 if j+1 < len(v) && v[j] == '.' && isDigit(v[j+1]) {
64 i = j + 1 64 i = j + 1
65 continue 65 continue
66 } 66 }
@@ -89,3 +89,5 @@ func rank(suffix string) int {
89 } 89 }
90 return -1 90 return -1
91} 91}
92
93func isDigit(c byte) bool { return c >= '0' && c <= '9' }
internal/lfs/lfs.go +4 −1
@@ -188,7 +188,10 @@ func Verify(secret []byte, token string, now time.Time) (Grant, bool) {
188 repoID, err1 := strconv.ParseInt(parts[0], 10, 64) 188 repoID, err1 := strconv.ParseInt(parts[0], 10, 64)
189 keyID, err2 := strconv.ParseInt(parts[1], 10, 64) 189 keyID, err2 := strconv.ParseInt(parts[1], 10, 64)
190 exp, err3 := strconv.ParseInt(parts[4], 10, 64) 190 exp, err3 := strconv.ParseInt(parts[4], 10, 64)
191 if err1 != nil || err2 != nil || err3 != nil || keyID < 0 || now.Unix() > exp { 191 if err1 != nil || err2 != nil || err3 != nil {
192 return Grant{}, false
193 }
194 if keyID < 0 || now.Unix() > exp {
192 return Grant{}, false 195 return Grant{}, false
193 } 196 }
194 if (keyID == 0) != (parts[2] == "") { 197 if (keyID == 0) != (parts[2] == "") {
internal/store/activity.go +7 −16
@@ -49,32 +49,18 @@ func (s *Store) RecordCommitActivity(repoID int64, sha string, userID int64, day
49// commits landed on default branches plus everything the events table 49// commits landed on default branches plus everything the events table
50// attributes to them (issues, MRs, comments, releases, pushes). 50// attributes to them (issues, MRs, comments, releases, pushes).
51func (s *Store) ActivityByDay(userID int64, sinceDay string) (map[string]int, error) { 51func (s *Store) ActivityByDay(userID int64, sinceDay string) (map[string]int, error) {
52 rows, err := s.DB.Query(` 52 return s.dayCounts(`
53 SELECT day, COUNT(*) FROM ( 53 SELECT day, COUNT(*) FROM (
54 SELECT day FROM commit_activity WHERE user_id = ?1 AND day >= ?2 54 SELECT day FROM commit_activity WHERE user_id = ?1 AND day >= ?2
55 UNION ALL 55 UNION ALL
56 SELECT date(created_at) AS day FROM events 56 SELECT date(created_at) AS day FROM events
57 WHERE actor_id = ?1 AND date(created_at) >= ?2 AND kind <> 'push' 57 WHERE actor_id = ?1 AND date(created_at) >= ?2 AND kind <> 'push'
58 ) GROUP BY day`, userID, sinceDay) 58 ) GROUP BY day`, userID, sinceDay)
59 if err != nil {
60 return nil, err
61 }
62 defer rows.Close()
63 out := map[string]int{}
64 for rows.Next() {
65 var day string
66 var n int
67 if err := rows.Scan(&day, &n); err != nil {
68 return nil, err
69 }
70 out[day] = n
71 }
72 return out, rows.Err()
73} 59}
74 60
75// OrgActivityByDay aggregates activity across an org's repositories. 61// OrgActivityByDay aggregates activity across an org's repositories.
76func (s *Store) OrgActivityByDay(orgID int64, sinceDay string) (map[string]int, error) { 62func (s *Store) OrgActivityByDay(orgID int64, sinceDay string) (map[string]int, error) {
77 rows, err := s.DB.Query(` 63 return s.dayCounts(`
78 SELECT day, COUNT(*) FROM ( 64 SELECT day, COUNT(*) FROM (
79 SELECT ca.day FROM commit_activity ca 65 SELECT ca.day FROM commit_activity ca
80 JOIN repos r ON r.id = ca.repo_id 66 JOIN repos r ON r.id = ca.repo_id
@@ -85,6 +71,11 @@ func (s *Store) OrgActivityByDay(orgID int64, sinceDay string) (map[string]int,
85 WHERE r.owner_kind = 'org' AND r.owner_id = ?1 71 WHERE r.owner_kind = 'org' AND r.owner_id = ?1
86 AND date(e.created_at) >= ?2 AND e.kind <> 'push' 72 AND date(e.created_at) >= ?2 AND e.kind <> 'push'
87 ) GROUP BY day`, orgID, sinceDay) 73 ) GROUP BY day`, orgID, sinceDay)
74}
75
76// dayCounts reads a query's (day, count) rows into a map.
77func (s *Store) dayCounts(query string, args ...any) (map[string]int, error) {
78 rows, err := s.DB.Query(query, args...)
88 if err != nil { 79 if err != nil {
89 return nil, err 80 return nil, err
90 } 81 }
internal/store/adminusers.go +1 −14
@@ -61,20 +61,7 @@ func (s *Store) ListUsers(state string, limit int, after string) ([]AdminUser, e
61 q += " LIMIT ?" 61 q += " LIMIT ?"
62 args = append(args, limit) 62 args = append(args, limit)
63 } 63 }
64 rows, err := s.DB.Query(q, args...) 64 return queryAll(s.DB, scanAdminUser, q, args...)
65 if err != nil {
66 return nil, err
67 }
68 defer rows.Close()
69 var out []AdminUser
70 for rows.Next() {
71 u, err := scanAdminUser(rows)
72 if err != nil {
73 return nil, err
74 }
75 out = append(out, u)
76 }
77 return out, rows.Err()
78} 65}
79 66
80// AdminUserByName is the ListUsers row for one account. 67// AdminUserByName is the ListUsers row for one account.
internal/store/bookmarks.go +1 −14
@@ -43,20 +43,7 @@ func (s *Store) BookmarkCount(repoID int64) int {
43// The caller filters by what the viewer may see: a bookmarked repository 43// The caller filters by what the viewer may see: a bookmarked repository
44// can since have gone private. 44// can since have gone private.
45func (s *Store) ListBookmarks(userID int64) ([]Repo, error) { 45func (s *Store) ListBookmarks(userID int64) ([]Repo, error) {
46 rows, err := s.DB.Query(repoSelect+` 46 return queryAll(s.DB, scanRepo, repoSelect+`
47 JOIN repo_bookmarks b ON b.repo_id = r.id 47 JOIN repo_bookmarks b ON b.repo_id = r.id
48 WHERE b.user_id = ? ORDER BY b.bookmarked_at DESC`, userID) 48 WHERE b.user_id = ? ORDER BY b.bookmarked_at DESC`, userID)
49 if err != nil {
50 return nil, err
51 }
52 defer rows.Close()
53 var out []Repo
54 for rows.Next() {
55 r, err := scanRepo(rows)
56 if err != nil {
57 return nil, err
58 }
59 out = append(out, r)
60 }
61 return out, rows.Err()
62} 49}
internal/store/builds.go +1 −14
@@ -348,20 +348,7 @@ func (s *Store) ListBuilds(repoID int64, f BuildFilter, limit int) ([]Build, err
348 } 348 }
349 q += " ORDER BY number DESC LIMIT ?" 349 q += " ORDER BY number DESC LIMIT ?"
350 args = append(args, limit) 350 args = append(args, limit)
351 rows, err := s.DB.Query(q, args...) 351 return queryAll(s.DB, scanBuild, q, args...)
352 if err != nil {
353 return nil, err
354 }
355 defer rows.Close()
356 var out []Build
357 for rows.Next() {
358 b, err := scanBuild(rows)
359 if err != nil {
360 return nil, err
361 }
362 out = append(out, b)
363 }
364 return out, rows.Err()
365} 352}
366 353
367// BuildLog returns the stored log bytes. 354// BuildLog returns the stored log bytes.
internal/store/dashboard.go +22 −80
@@ -115,22 +115,9 @@ func (s *Store) UnpinRepo(userID, repoID int64) error {
115// PinnedRepos returns the user's pinned repositories in pin order. The 115// PinnedRepos returns the user's pinned repositories in pin order. The
116// caller applies visibility checks before rendering. 116// caller applies visibility checks before rendering.
117func (s *Store) PinnedRepos(userID int64) ([]Repo, error) { 117func (s *Store) PinnedRepos(userID int64) ([]Repo, error) {
118 rows, err := s.DB.Query(repoSelect+` 118 return queryAll(s.DB, scanRepo, repoSelect+`
119 JOIN repo_pins p ON p.repo_id = r.id AND p.user_id = ? 119 JOIN repo_pins p ON p.repo_id = r.id AND p.user_id = ?
120 ORDER BY p.pinned_at`, userID) 120 ORDER BY p.pinned_at`, userID)
121 if err != nil {
122 return nil, err
123 }
124 defer rows.Close()
125 var out []Repo
126 for rows.Next() {
127 r, err := scanRepo(rows)
128 if err != nil {
129 return nil, err
130 }
131 out = append(out, r)
132 }
133 return out, rows.Err()
134} 121}
135 122
136// reviewQueueQuery is ReviewQueue's involved half: open merge requests the 123// reviewQueueQuery is ReviewQueue's involved half: open merge requests the
@@ -304,29 +291,8 @@ type FeedEvent struct {
304// newest first, for readers carrying no session. Push events are 291// newest first, for readers carrying no session. Push events are
305// excluded as in RecentEvents. 292// excluded as in RecentEvents.
306func (s *Store) OwnerPublicEvents(ownerKind string, ownerID int64, limit int) ([]FeedEvent, error) { 293func (s *Store) OwnerPublicEvents(ownerKind string, ownerID int64, limit int) ([]FeedEvent, error) {
307 rows, err := s.DB.Query(` 294 return queryAll(s.DB, scanFeedEvent, feedSelect+`r.visibility = 'public' AND r.owner_kind = ? AND r.owner_id = ?
308 SELECT e.id, COALESCE(u.username, o.name) || '/' || r.name,
309 COALESCE(ac.username, ''), e.kind, e.data_json, e.created_at
310 FROM events e
311 JOIN repos r ON r.id = e.repo_id
312 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
313 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id
314 LEFT JOIN users ac ON ac.id = e.actor_id
315 WHERE e.kind <> 'push' AND r.visibility = 'public' AND r.owner_kind = ? AND r.owner_id = ?
316 ORDER BY e.id DESC LIMIT ?`, ownerKind, ownerID, limit) 295 ORDER BY e.id DESC LIMIT ?`, ownerKind, ownerID, limit)
317 if err != nil {
318 return nil, err
319 }
320 defer rows.Close()
321 var out []FeedEvent
322 for rows.Next() {
323 var e FeedEvent
324 if err := rows.Scan(&e.ID, &e.RepoPath, &e.Actor, &e.Kind, &e.Data, &e.CreatedAt); err != nil {
325 return nil, err
326 }
327 out = append(out, e)
328 }
329 return out, rows.Err()
330} 296}
331 297
332// UserPublicEvents returns what a user did on public repositories, 298// UserPublicEvents returns what a user did on public repositories,
@@ -335,29 +301,8 @@ func (s *Store) OwnerPublicEvents(ownerKind string, ownerID int64, limit int) ([
335// agree with the total printed above its graph. Push events are 301// agree with the total printed above its graph. Push events are
336// excluded as in RecentEvents. 302// excluded as in RecentEvents.
337func (s *Store) UserPublicEvents(userID int64, limit int) ([]FeedEvent, error) { 303func (s *Store) UserPublicEvents(userID int64, limit int) ([]FeedEvent, error) {
338 rows, err := s.DB.Query(` 304 return queryAll(s.DB, scanFeedEvent, feedSelect+`r.visibility = 'public' AND e.actor_id = ?
339 SELECT e.id, COALESCE(u.username, o.name) || '/' || r.name,
340 COALESCE(ac.username, ''), e.kind, e.data_json, e.created_at
341 FROM events e
342 JOIN repos r ON r.id = e.repo_id
343 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
344 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id
345 LEFT JOIN users ac ON ac.id = e.actor_id
346 WHERE e.kind <> 'push' AND r.visibility = 'public' AND e.actor_id = ?
347 ORDER BY e.id DESC LIMIT ?`, userID, limit) 305 ORDER BY e.id DESC LIMIT ?`, userID, limit)
348 if err != nil {
349 return nil, err
350 }
351 defer rows.Close()
352 var out []FeedEvent
353 for rows.Next() {
354 var e FeedEvent
355 if err := rows.Scan(&e.ID, &e.RepoPath, &e.Actor, &e.Kind, &e.Data, &e.CreatedAt); err != nil {
356 return nil, err
357 }
358 out = append(out, e)
359 }
360 return out, rows.Err()
361} 306}
362 307
363// RecentEvents returns activity on repositories the user can reach. Push 308// RecentEvents returns activity on repositories the user can reach. Push
@@ -365,7 +310,19 @@ func (s *Store) UserPublicEvents(userID int64, limit int) ([]FeedEvent, error) {
365// before (an event id) starts the page strictly below it, matching the 310// before (an event id) starts the page strictly below it, matching the
366// id-descending order; 0 starts at the newest. 311// id-descending order; 0 starts at the newest.
367func (s *Store) RecentEvents(userID int64, limit int, before int64) ([]FeedEvent, error) { 312func (s *Store) RecentEvents(userID int64, limit int, before int64) ([]FeedEvent, error) {
368 q := ` 313 q := feedSelect + reachableCond
314 args := []any{userID, limit}
315 if before > 0 {
316 q += " AND e.id < ?3"
317 args = append(args, before)
318 }
319 q += " ORDER BY e.id DESC LIMIT ?2"
320 return queryAll(s.DB, scanFeedEvent, q, args...)
321}
322
323// feedSelect reads FeedEvents, push events left out; callers append the
324// rest of the WHERE clause.
325const feedSelect = `
369 SELECT e.id, COALESCE(u.username, o.name) || '/' || r.name, 326 SELECT e.id, COALESCE(u.username, o.name) || '/' || r.name,
370 COALESCE(ac.username, ''), e.kind, e.data_json, e.created_at 327 COALESCE(ac.username, ''), e.kind, e.data_json, e.created_at
371 FROM events e 328 FROM events e
@@ -373,25 +330,10 @@ func (s *Store) RecentEvents(userID int64, limit int, before int64) ([]FeedEvent
373 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id 330 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
374 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id 331 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id
375 LEFT JOIN users ac ON ac.id = e.actor_id 332 LEFT JOIN users ac ON ac.id = e.actor_id
376 WHERE e.kind <> 'push' AND ` + reachableCond 333 WHERE e.kind <> 'push' AND `
377 args := []any{userID, limit} 334
378 if before > 0 { 335func scanFeedEvent(row interface{ Scan(...any) error }) (FeedEvent, error) {
379 q += " AND e.id < ?3" 336 var e FeedEvent
380 args = append(args, before) 337 err := row.Scan(&e.ID, &e.RepoPath, &e.Actor, &e.Kind, &e.Data, &e.CreatedAt)
381 } 338 return e, err
382 q += " ORDER BY e.id DESC LIMIT ?2"
383 rows, err := s.DB.Query(q, args...)
384 if err != nil {
385 return nil, err
386 }
387 defer rows.Close()
388 var out []FeedEvent
389 for rows.Next() {
390 var e FeedEvent
391 if err := rows.Scan(&e.ID, &e.RepoPath, &e.Actor, &e.Kind, &e.Data, &e.CreatedAt); err != nil {
392 return nil, err
393 }
394 out = append(out, e)
395 }
396 return out, rows.Err()
397} 339}
internal/store/diffcomments.go +1 −14
@@ -69,26 +69,13 @@ func (s *Store) AddDiffComment(mrID, authorID int64, headSHA, path, side string,
69// see: everything published, plus their own pending ones. viewer 0 is an 69// see: everything published, plus their own pending ones. viewer 0 is an
70// anonymous reader, who sees only what is published. 70// anonymous reader, who sees only what is published.
71func (s *Store) ListDiffComments(mrID, viewer int64) ([]DiffComment, error) { 71func (s *Store) ListDiffComments(mrID, viewer int64) ([]DiffComment, error) {
72 rows, err := s.DB.Query(` 72 return queryAll(s.DB, scanDiffComment, `
73 SELECT `+diffCommentCols+` 73 SELECT `+diffCommentCols+`
74 FROM mr_diff_comments c 74 FROM mr_diff_comments c
75 JOIN users u ON u.id = c.author_id 75 JOIN users u ON u.id = c.author_id
76 LEFT JOIN users r ON r.id = c.resolved_by 76 LEFT JOIN users r ON r.id = c.resolved_by
77 WHERE c.mr_id = ?1 AND (c.pending = 0 OR c.author_id = ?2) 77 WHERE c.mr_id = ?1 AND (c.pending = 0 OR c.author_id = ?2)
78 ORDER BY c.id`, mrID, viewer) 78 ORDER BY c.id`, mrID, viewer)
79 if err != nil {
80 return nil, err
81 }
82 defer rows.Close()
83 var out []DiffComment
84 for rows.Next() {
85 c, err := scanDiffComment(rows)
86 if err != nil {
87 return nil, err
88 }
89 out = append(out, c)
90 }
91 return out, rows.Err()
92} 79}
93 80
94const diffCommentCols = `c.id, u.username, c.head_sha, c.path, c.side, c.line, c.start_line, c.body, 81const diffCommentCols = `c.id, u.username, c.head_sha, c.path, c.side, c.line, c.start_line, c.body,
internal/store/mergequeue.go +1 −10
@@ -86,14 +86,5 @@ func (s *Store) QueuedMRsAtHead(repoID int64, sha string) ([]int64, error) {
86 if err != nil { 86 if err != nil {
87 return nil, err 87 return nil, err
88 } 88 }
89 defer rows.Close() 89 return scanIDs(rows)
90 var ids []int64
91 for rows.Next() {
92 var id int64
93 if err := rows.Scan(&id); err != nil {
94 return nil, err
95 }
96 ids = append(ids, id)
97 }
98 return ids, rows.Err()
99} 90}
internal/store/milestones.go +1 −14
@@ -172,20 +172,7 @@ func (s *Store) listMilestones(where string, args []any, state string, readable
172 qargs = append(qargs, state) 172 qargs = append(qargs, state)
173 } 173 }
174 q += " ORDER BY m.org_id IS NULL, m.due_date = '', m.due_date, m.title" 174 q += " ORDER BY m.org_id IS NULL, m.due_date = '', m.due_date, m.title"
175 rows, err := s.DB.Query(q, qargs...) 175 return queryAll(s.DB, scanMilestone, q, qargs...)
176 if err != nil {
177 return nil, err
178 }
179 defer rows.Close()
180 var out []Milestone
181 for rows.Next() {
182 m, err := scanMilestone(rows)
183 if err != nil {
184 return nil, err
185 }
186 out = append(out, m)
187 }
188 return out, rows.Err()
189} 176}
190 177
191// ListMilestones lists the milestones a repository sees, the org's first, 178// ListMilestones lists the milestones a repository sees, the org's first,
internal/store/mirrors.go +1 −14
@@ -74,20 +74,7 @@ func (s *Store) scanMirror(row interface{ Scan(...any) error }) (Mirror, error)
74} 74}
75 75
76func (s *Store) mirrorQuery(q string, args ...any) ([]Mirror, error) { 76func (s *Store) mirrorQuery(q string, args ...any) ([]Mirror, error) {
77 rows, err := s.DB.Query(q, args...) 77 return queryAll(s.DB, s.scanMirror, q, args...)
78 if err != nil {
79 return nil, err
80 }
81 defer rows.Close()
82 var out []Mirror
83 for rows.Next() {
84 m, err := s.scanMirror(rows)
85 if err != nil {
86 return nil, err
87 }
88 out = append(out, m)
89 }
90 return out, rows.Err()
91} 78}
92 79
93func (s *Store) ListMirrors(repoID int64) ([]Mirror, error) { 80func (s *Store) ListMirrors(repoID int64) ([]Mirror, error) {
internal/store/mrs.go +9 −74
@@ -231,62 +231,23 @@ func (s *Store) QueryMRs(repoID int64, f MRFilter) ([]MR, error) {
231 q += " LIMIT ?" 231 q += " LIMIT ?"
232 args = append(args, f.Limit) 232 args = append(args, f.Limit)
233 } 233 }
234 rows, err := s.DB.Query(q, args...) 234 return queryAll(s.DB, scanMR, q, args...)
235 if err != nil {
236 return nil, err
237 }
238 defer rows.Close()
239 var out []MR
240 for rows.Next() {
241 m, err := scanMR(rows)
242 if err != nil {
243 return nil, err
244 }
245 out = append(out, m)
246 }
247 return out, rows.Err()
248} 235}
249 236
250// OpenMRsBySource returns open (and source_gone) MRs fed by the given source 237// OpenMRsBySource returns open (and source_gone) MRs fed by the given source
251// repo branch — the cross-repo hook effect consults this. 238// repo branch — the cross-repo hook effect consults this.
252func (s *Store) OpenMRsBySource(sourceRepoID int64, sourceRef string) ([]MR, error) { 239func (s *Store) OpenMRsBySource(sourceRepoID int64, sourceRef string) ([]MR, error) {
253 rows, err := s.DB.Query( 240 return queryAll(s.DB, scanMR,
254 mrSelect+" WHERE m.source_repo_id = ? AND m.source_ref = ? AND m.state IN ('open','source_gone')", 241 mrSelect+" WHERE m.source_repo_id = ? AND m.source_ref = ? AND m.state IN ('open','source_gone')",
255 sourceRepoID, sourceRef) 242 sourceRepoID, sourceRef)
256 if err != nil {
257 return nil, err
258 }
259 defer rows.Close()
260 var out []MR
261 for rows.Next() {
262 m, err := scanMR(rows)
263 if err != nil {
264 return nil, err
265 }
266 out = append(out, m)
267 }
268 return out, rows.Err()
269} 243}
270 244
271// UnmergedMRsByTarget returns the open and source_gone MRs in repoID 245// UnmergedMRsByTarget returns the open and source_gone MRs in repoID
272// targeting targetRef, oldest first. 246// targeting targetRef, oldest first.
273func (s *Store) UnmergedMRsByTarget(repoID int64, targetRef string) ([]MR, error) { 247func (s *Store) UnmergedMRsByTarget(repoID int64, targetRef string) ([]MR, error) {
274 rows, err := s.DB.Query( 248 return queryAll(s.DB, scanMR,
275 mrSelect+" WHERE m.repo_id = ? AND m.target_ref = ? AND m.state IN ('open','source_gone') ORDER BY m.number", 249 mrSelect+" WHERE m.repo_id = ? AND m.target_ref = ? AND m.state IN ('open','source_gone') ORDER BY m.number",
276 repoID, targetRef) 250 repoID, targetRef)
277 if err != nil {
278 return nil, err
279 }
280 defer rows.Close()
281 var out []MR
282 for rows.Next() {
283 m, err := scanMR(rows)
284 if err != nil {
285 return nil, err
286 }
287 out = append(out, m)
288 }
289 return out, rows.Err()
290} 251}
291 252
292// MarkMerged records the merge along with the target tip it landed on, so 253// MarkMerged records the merge along with the target tip it landed on, so
@@ -332,20 +293,7 @@ func (s *Store) SetSupersededBy(mrID, n int64) error {
332// superseded_by names number, oldest first — the reverse of 293// superseded_by names number, oldest first — the reverse of
333// MR.SupersededBy. 294// MR.SupersededBy.
334func (s *Store) MRsSuperseding(repoID, number int64) ([]MR, error) { 295func (s *Store) MRsSuperseding(repoID, number int64) ([]MR, error) {
335 rows, err := s.DB.Query(mrSelect+" WHERE m.repo_id = ? AND m.superseded_by = ? ORDER BY m.number ASC", repoID, number) 296 return queryAll(s.DB, scanMR, mrSelect+" WHERE m.repo_id = ? AND m.superseded_by = ? ORDER BY m.number ASC", repoID, number)
336 if err != nil {
337 return nil, err
338 }
339 defer rows.Close()
340 var out []MR
341 for rows.Next() {
342 m, err := scanMR(rows)
343 if err != nil {
344 return nil, err
345 }
346 out = append(out, m)
347 }
348 return out, rows.Err()
349} 297}
350 298
351// SetMRState moves an MR between states that carry no resolution stamp. 299// SetMRState moves an MR between states that carry no resolution stamp.
@@ -443,24 +391,11 @@ func (s *Store) MRHeads(mrID int64) ([]MRHead, error) {
443// target on every read, so nothing else has to move; an approval, 391// target on every read, so nothing else has to move; an approval,
444// though, was of the diff against the old branch. 392// though, was of the diff against the old branch.
445func (s *Store) SetMRTarget(mrID int64, targetRef string) error { 393func (s *Store) SetMRTarget(mrID int64, targetRef string) error {
446 tx, err := s.DB.Begin() 394 return s.execAll(
447 if err != nil { 395 stmt{"UPDATE merge_requests SET target_ref = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?",
448 return err 396 []any{targetRef, mrID}},
449 } 397 stmt{"UPDATE mr_reviews SET stale = 1 WHERE mr_id = ?", []any{mrID}},
450 defer tx.Rollback() 398 )
451 res, err := tx.Exec(
452 "UPDATE merge_requests SET target_ref = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?",
453 targetRef, mrID)
454 if err != nil {
455 return err
456 }
457 if n, _ := res.RowsAffected(); n == 0 {
458 return ErrNotFound
459 }
460 if _, err := tx.Exec("UPDATE mr_reviews SET stale = 1 WHERE mr_id = ?", mrID); err != nil {
461 return err
462 }
463 return tx.Commit()
464} 399}
465 400
466// MarkSourceGoneForRepo flags every open MR sourced from the repo; called 401// MarkSourceGoneForRepo flags every open MR sourced from the repo; called
internal/store/notify.go +7 −14
@@ -26,24 +26,11 @@ func (s *Store) EnqueueMailReplyTo(recipient, replyTo, subject, body string) err
26} 26}
27 27
28func (s *Store) DueMail(limit int) ([]QueuedMail, error) { 28func (s *Store) DueMail(limit int) ([]QueuedMail, error) {
29 rows, err := s.DB.Query(` 29 return queryAll(s.DB, scanQueuedMail, `
30 SELECT id, recipient, reply_to, subject, body, attempts FROM notifications 30 SELECT id, recipient, reply_to, subject, body, attempts FROM notifications
31 WHERE sent_at IS NULL AND failed_at IS NULL 31 WHERE sent_at IS NULL AND failed_at IS NULL
32 AND (next_attempt_at IS NULL OR next_attempt_at <= ?) 32 AND (next_attempt_at IS NULL OR next_attempt_at <= ?)
33 ORDER BY id LIMIT ?`, fmtTime(time.Now()), limit) 33 ORDER BY id LIMIT ?`, fmtTime(time.Now()), limit)
34 if err != nil {
35 return nil, err
36 }
37 defer rows.Close()
38 var out []QueuedMail
39 for rows.Next() {
40 var m QueuedMail
41 if err := rows.Scan(&m.ID, &m.Recipient, &m.ReplyTo, &m.Subject, &m.Body, &m.Attempts); err != nil {
42 return nil, err
43 }
44 out = append(out, m)
45 }
46 return out, rows.Err()
47} 34}
48 35
49func (s *Store) MarkMailSent(id int64) error { 36func (s *Store) MarkMailSent(id int64) error {
@@ -124,3 +111,9 @@ func (s *Store) idQuery(q string, args ...any) ([]int64, error) {
124 } 111 }
125 return out, rows.Err() 112 return out, rows.Err()
126} 113}
114
115func scanQueuedMail(row interface{ Scan(...any) error }) (QueuedMail, error) {
116 var m QueuedMail
117 err := row.Scan(&m.ID, &m.Recipient, &m.ReplyTo, &m.Subject, &m.Body, &m.Attempts)
118 return m, err
119}
internal/store/pagedomains.go +1 −14
@@ -92,20 +92,7 @@ func (s *Store) VerifyPageDomain(domain string, repoID int64) error {
92} 92}
93 93
94func (s *Store) ListPageDomains(repoID int64) ([]PageDomain, error) { 94func (s *Store) ListPageDomains(repoID int64) ([]PageDomain, error) {
95 rows, err := s.DB.Query(pageDomainSelect+" WHERE repo_id = ? ORDER BY domain", repoID) 95 return queryAll(s.DB, scanPageDomain, pageDomainSelect+" WHERE repo_id = ? ORDER BY domain", repoID)
96 if err != nil {
97 return nil, err
98 }
99 defer rows.Close()
100 var out []PageDomain
101 for rows.Next() {
102 d, err := scanPageDomain(rows)
103 if err != nil {
104 return nil, err
105 }
106 out = append(out, d)
107 }
108 return out, rows.Err()
109} 96}
110 97
111// PageDomainRepo resolves a request host to the repo serving it. Only 98// PageDomainRepo resolves a request host to the repo serving it. Only
internal/store/push.go +15 −17
@@ -167,7 +167,7 @@ func (s *Store) EnqueuePush(userID int64, title, body, path string) error {
167} 167}
168 168
169func (s *Store) DuePush(limit int) ([]QueuedPush, error) { 169func (s *Store) DuePush(limit int) ([]QueuedPush, error) {
170 rows, err := s.DB.Query(` 170 return queryAll(s.DB, s.scanQueuedPush, `
171 SELECT q.id, q.device_id, d.token, d.user_id, COALESCE(d.token_hash, ''), u.username, q.title, q.body, q.path, q.attempts, 171 SELECT q.id, q.device_id, d.token, d.user_id, COALESCE(d.token_hash, ''), u.username, q.title, q.body, q.path, q.attempts,
172 (SELECT COUNT(*) FROM inbox WHERE user_id = d.user_id AND read_at IS NULL) 172 (SELECT COUNT(*) FROM inbox WHERE user_id = d.user_id AND read_at IS NULL)
173 FROM push_queue q 173 FROM push_queue q
@@ -176,24 +176,22 @@ func (s *Store) DuePush(limit int) ([]QueuedPush, error) {
176 WHERE q.sent_at IS NULL AND q.failed_at IS NULL 176 WHERE q.sent_at IS NULL AND q.failed_at IS NULL
177 AND (q.next_attempt_at IS NULL OR q.next_attempt_at <= ?) 177 AND (q.next_attempt_at IS NULL OR q.next_attempt_at <= ?)
178 ORDER BY q.id LIMIT ?`, fmtTime(time.Now()), limit) 178 ORDER BY q.id LIMIT ?`, fmtTime(time.Now()), limit)
179}
180
181// scanQueuedPush reads a due push and opens its device token.
182func (s *Store) scanQueuedPush(row interface{ Scan(...any) error }) (QueuedPush, error) {
183 var p QueuedPush
184 var uid int64
185 var h string
186 if err := row.Scan(&p.ID, &p.DeviceID, &p.Token, &uid, &h, &p.Username, &p.Title, &p.Body, &p.Path, &p.Attempts, &p.Badge); err != nil {
187 return p, err
188 }
189 token, err := s.openValue(pushTokenAAD(uid, h), p.Token)
179 if err != nil { 190 if err != nil {
180 return nil, err 191 return p, fmt.Errorf("push device %d: %w", p.DeviceID, err)
181 }
182 defer rows.Close()
183 var out []QueuedPush
184 for rows.Next() {
185 var p QueuedPush
186 var uid int64
187 var h string
188 if err := rows.Scan(&p.ID, &p.DeviceID, &p.Token, &uid, &h, &p.Username, &p.Title, &p.Body, &p.Path, &p.Attempts, &p.Badge); err != nil {
189 return nil, err
190 }
191 if p.Token, err = s.openValue(pushTokenAAD(uid, h), p.Token); err != nil {
192 return nil, fmt.Errorf("push device %d: %w", p.DeviceID, err)
193 }
194 out = append(out, p)
195 } 192 }
196 return out, rows.Err() 193 p.Token = token
194 return p, nil
197} 195}
198 196
199func (s *Store) MarkPushSent(id int64) error { 197func (s *Store) MarkPushSent(id int64) error {
internal/store/repos.go +4 −56
@@ -257,20 +257,7 @@ func (s *Store) ListReposForUser(userID int64, limit int, after string) ([]Repo,
257 q += " LIMIT ?" 257 q += " LIMIT ?"
258 args = append(args, limit) 258 args = append(args, limit)
259 } 259 }
260 rows, err := s.DB.Query(q, args...) 260 return queryAll(s.DB, scanRepo, q, args...)
261 if err != nil {
262 return nil, err
263 }
264 defer rows.Close()
265 var out []Repo
266 for rows.Next() {
267 r, err := scanRepo(rows)
268 if err != nil {
269 return nil, err
270 }
271 out = append(out, r)
272 }
273 return out, rows.Err()
274} 261}
275 262
276// AccessRole returns the user's effective role on the repo ("" if none): 263// AccessRole returns the user's effective role on the repo ("" if none):
@@ -444,20 +431,7 @@ func (s *Store) RepoByID(id int64) (Repo, error) {
444 431
445// ListPublicRepos returns all public repositories, for the anonymous index. 432// ListPublicRepos returns all public repositories, for the anonymous index.
446func (s *Store) ListPublicRepos() ([]Repo, error) { 433func (s *Store) ListPublicRepos() ([]Repo, error) {
447 rows, err := s.DB.Query(repoSelect + " WHERE r.visibility = 'public' ORDER BY 4, r.name") 434 return queryAll(s.DB, scanRepo, repoSelect+" WHERE r.visibility = 'public' ORDER BY 4, r.name")
448 if err != nil {
449 return nil, err
450 }
451 defer rows.Close()
452 var out []Repo
453 for rows.Next() {
454 r, err := scanRepo(rows)
455 if err != nil {
456 return nil, err
457 }
458 out = append(out, r)
459 }
460 return out, rows.Err()
461} 435}
462 436
463// ListPublicReposByActivity returns all public repositories, the most 437// ListPublicReposByActivity returns all public repositories, the most
@@ -486,20 +460,7 @@ func (s *Store) ListPublicReposByActivity() ([]Repo, error) {
486// ListForks returns the repositories forked from one repo. The caller 460// ListForks returns the repositories forked from one repo. The caller
487// filters by what the viewer may see. 461// filters by what the viewer may see.
488func (s *Store) ListForks(repoID int64) ([]Repo, error) { 462func (s *Store) ListForks(repoID int64) ([]Repo, error) {
489 rows, err := s.DB.Query(repoSelect+" WHERE r.fork_of = ? ORDER BY 4, r.name", repoID) 463 return queryAll(s.DB, scanRepo, repoSelect+" WHERE r.fork_of = ? ORDER BY 4, r.name", repoID)
490 if err != nil {
491 return nil, err
492 }
493 defer rows.Close()
494 var out []Repo
495 for rows.Next() {
496 r, err := scanRepo(rows)
497 if err != nil {
498 return nil, err
499 }
500 out = append(out, r)
501 }
502 return out, rows.Err()
503} 464}
504 465
505func (s *Store) UpdateDefaultBranch(repoID int64, branch string) error { 466func (s *Store) UpdateDefaultBranch(repoID int64, branch string) error {
@@ -510,21 +471,8 @@ func (s *Store) UpdateDefaultBranch(repoID int64, branch string) error {
510// ListReposForOwner returns every repo owned by one user or org; the caller 471// ListReposForOwner returns every repo owned by one user or org; the caller
511// filters by viewer visibility. 472// filters by viewer visibility.
512func (s *Store) ListReposForOwner(ownerKind string, ownerID int64) ([]Repo, error) { 473func (s *Store) ListReposForOwner(ownerKind string, ownerID int64) ([]Repo, error) {
513 rows, err := s.DB.Query(repoSelect+" WHERE r.owner_kind = ? AND r.owner_id = ? ORDER BY r.name", 474 return queryAll(s.DB, scanRepo, repoSelect+" WHERE r.owner_kind = ? AND r.owner_id = ? ORDER BY r.name",
514 ownerKind, ownerID) 475 ownerKind, ownerID)
515 if err != nil {
516 return nil, err
517 }
518 defer rows.Close()
519 var out []Repo
520 for rows.Next() {
521 r, err := scanRepo(rows)
522 if err != nil {
523 return nil, err
524 }
525 out = append(out, r)
526 }
527 return out, rows.Err()
528} 476}
529 477
530// RenameRepo changes a repository's name under the same owner. The unique 478// RenameRepo changes a repository's name under the same owner. The unique
internal/store/search.go +1 −14
@@ -11,20 +11,7 @@ const visibleCond = `(r.visibility = 'public' OR ` + reachableCond + `)`
11// VisibleRepos returns every repository the user may read, public ones 11// VisibleRepos returns every repository the user may read, public ones
12// included, ordered by owner then name. 12// included, ordered by owner then name.
13func (s *Store) VisibleRepos(userID int64) ([]Repo, error) { 13func (s *Store) VisibleRepos(userID int64) ([]Repo, error) {
14 rows, err := s.DB.Query(repoSelect+" WHERE "+visibleCond+" ORDER BY 4, r.name", userID) 14 return queryAll(s.DB, scanRepo, repoSelect+" WHERE "+visibleCond+" ORDER BY 4, r.name", userID)
15 if err != nil {
16 return nil, err
17 }
18 defer rows.Close()
19 var out []Repo
20 for rows.Next() {
21 r, err := scanRepo(rows)
22 if err != nil {
23 return nil, err
24 }
25 out = append(out, r)
26 }
27 return out, rows.Err()
28} 15}
29 16
30// SearchIssues returns issues matching q in title or body, newest 17// SearchIssues returns issues matching q in title or body, newest
internal/store/snippets.go +4 −16
@@ -206,20 +206,8 @@ func (s *Store) SetSnippetFile(id int64, name string, content []byte) error {
206} 206}
207 207
208func (s *Store) RemoveSnippetFile(id int64, name string) error { 208func (s *Store) RemoveSnippetFile(id int64, name string) error {
209 tx, err := s.DB.Begin() 209 return s.execAll(
210 if err != nil { 210 stmt{"DELETE FROM snippet_files WHERE snippet_id = ? AND name = ?", []any{id, name}},
211 return err 211 stmt{"UPDATE snippets SET updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?", []any{id}},
212 } 212 )
213 defer tx.Rollback()
214 res, err := tx.Exec("DELETE FROM snippet_files WHERE snippet_id = ? AND name = ?", id, name)
215 if err != nil {
216 return err
217 }
218 if n, _ := res.RowsAffected(); n == 0 {
219 return ErrNotFound
220 }
221 if _, err := tx.Exec("UPDATE snippets SET updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?", id); err != nil {
222 return err
223 }
224 return tx.Commit()
225} 213}
internal/store/stack.go +1 −14
@@ -12,22 +12,9 @@ import (
12// OpenMRsByTarget lists the open merge requests in repoID targeting 12// OpenMRsByTarget lists the open merge requests in repoID targeting
13// targetRef, oldest first. 13// targetRef, oldest first.
14func (s *Store) OpenMRsByTarget(repoID int64, targetRef string) ([]MR, error) { 14func (s *Store) OpenMRsByTarget(repoID int64, targetRef string) ([]MR, error) {
15 rows, err := s.DB.Query( 15 return queryAll(s.DB, scanMR,
16 mrSelect+" WHERE m.repo_id = ? AND m.target_ref = ? AND m.state = 'open' ORDER BY m.number", 16 mrSelect+" WHERE m.repo_id = ? AND m.target_ref = ? AND m.state = 'open' ORDER BY m.number",
17 repoID, targetRef) 17 repoID, targetRef)
18 if err != nil {
19 return nil, err
20 }
21 defer rows.Close()
22 var out []MR
23 for rows.Next() {
24 m, err := scanMR(rows)
25 if err != nil {
26 return nil, err
27 }
28 out = append(out, m)
29 }
30 return out, rows.Err()
31} 18}
32 19
33// OpenMRBySource finds the open merge request in repoID whose source is 20// OpenMRBySource finds the open merge request in repoID whose source is
internal/store/stats.go +1 −14
@@ -2,20 +2,7 @@ package store
2 2
3// ListAllRepos returns every repository, for host-local admin tooling. 3// ListAllRepos returns every repository, for host-local admin tooling.
4func (s *Store) ListAllRepos() ([]Repo, error) { 4func (s *Store) ListAllRepos() ([]Repo, error) {
5 rows, err := s.DB.Query(repoSelect + " ORDER BY 4, r.name") 5 return queryAll(s.DB, scanRepo, repoSelect+" ORDER BY 4, r.name")
6 if err != nil {
7 return nil, err
8 }
9 defer rows.Close()
10 var out []Repo
11 for rows.Next() {
12 r, err := scanRepo(rows)
13 if err != nil {
14 return nil, err
15 }
16 out = append(out, r)
17 }
18 return out, rows.Err()
19} 6}
20 7
21type Counts struct { 8type Counts struct {
internal/store/statuses.go +7 −14
@@ -34,23 +34,10 @@ func (s *Store) SetCommitStatus(repoID int64, sha, context, state, description,
34 34
35// ListCommitStatuses returns the latest status per context for a commit. 35// ListCommitStatuses returns the latest status per context for a commit.
36func (s *Store) ListCommitStatuses(repoID int64, sha string) ([]CommitStatus, error) { 36func (s *Store) ListCommitStatuses(repoID int64, sha string) ([]CommitStatus, error) {
37 rows, err := s.DB.Query(` 37 return queryAll(s.DB, scanCommitStatus, `
38 SELECT cs.context, cs.state, cs.description, cs.target_url, COALESCE(u.username, ''), cs.updated_at 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 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) 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} 41}
55 42
56// CommitStatusesFor is ListCommitStatuses for every commit on a list 43// CommitStatusesFor is ListCommitStatuses for every commit on a list
@@ -188,3 +175,9 @@ func (s *Store) ChecksForCommit(repoID int64, sha string) ([]Check, string, erro
188 } 175 }
189 return checks, CombinedStatus(statuses), nil 176 return checks, CombinedStatus(statuses), nil
190} 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}
internal/store/store.go +53 −3
@@ -311,7 +311,57 @@ func (s *Store) migrateStep(sqlText string, newVersion int, fkOff bool) (retErr
311func IsInternal(err error) bool { 311func IsInternal(err error) bool {
312 var sqlErr *sqlite.Error 312 var sqlErr *sqlite.Error
313 var pathErr *fs.PathError 313 var pathErr *fs.PathError
314 return errors.As(err, &sqlErr) || errors.As(err, &pathErr) || 314 if errors.As(err, &sqlErr) || errors.As(err, &pathErr) {
315 errors.Is(err, sql.ErrTxDone) || errors.Is(err, sql.ErrConnDone) || 315 return true
316 errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) 316 }
317 for _, target := range []error{sql.ErrTxDone, sql.ErrConnDone, context.DeadlineExceeded, context.Canceled} {
318 if errors.Is(err, target) {
319 return true
320 }
321 }
322 return false
323}
324
325// stmt is one statement and its arguments.
326type stmt struct {
327 query string
328 args []any
329}
330
331// execAll runs stmts in one transaction. The first must change a row;
332// when it changes none, nothing is kept and the error is ErrNotFound.
333func (s *Store) execAll(stmts ...stmt) error {
334 tx, err := s.DB.Begin()
335 if err != nil {
336 return err
337 }
338 defer tx.Rollback()
339 for i, st := range stmts {
340 res, err := tx.Exec(st.query, st.args...)
341 if err != nil {
342 return err
343 }
344 if n, _ := res.RowsAffected(); i == 0 && n == 0 {
345 return ErrNotFound
346 }
347 }
348 return tx.Commit()
349}
350
351// queryAll runs query on q and reads every row it returns with scan.
352func queryAll[T any](q queryer, scan func(interface{ Scan(...any) error }) (T, error), query string, args ...any) ([]T, error) {
353 rows, err := q.Query(query, args...)
354 if err != nil {
355 return nil, err
356 }
357 defer rows.Close()
358 var out []T
359 for rows.Next() {
360 v, err := scan(rows)
361 if err != nil {
362 return nil, err
363 }
364 out = append(out, v)
365 }
366 return out, rows.Err()
317} 367}
internal/store/webhooks.go +21 −30
@@ -106,7 +106,7 @@ func (s *Store) RemoveWebhook(repoID, hookID int64) error {
106// DueDeliveries returns pending deliveries whose time has come, with the 106// DueDeliveries returns pending deliveries whose time has come, with the
107// event and hook context needed to send them. 107// event and hook context needed to send them.
108func (s *Store) DueDeliveries(limit int) ([]Delivery, error) { 108func (s *Store) DueDeliveries(limit int) ([]Delivery, error) {
109 rows, err := s.DB.Query(` 109 return queryAll(s.DB, s.scanDelivery, `
110 SELECT d.id, d.webhook_id, w.url, w.secret, d.event_id, e.kind, 110 SELECT d.id, d.webhook_id, w.url, w.secret, d.event_id, e.kind,
111 COALESCE(u2.username, o.name, '') || '/' || COALESCE(r.name, ''), 111 COALESCE(u2.username, o.name, '') || '/' || COALESCE(r.name, ''),
112 COALESCE(u.username, ''), e.data_json, e.created_at, d.attempts 112 COALESCE(u.username, ''), e.data_json, e.created_at, d.attempts
@@ -120,23 +120,21 @@ func (s *Store) DueDeliveries(limit int) ([]Delivery, error) {
120 WHERE d.delivered_at IS NULL AND d.failed_at IS NULL 120 WHERE d.delivered_at IS NULL AND d.failed_at IS NULL
121 AND (d.next_attempt_at IS NULL OR d.next_attempt_at <= ?) 121 AND (d.next_attempt_at IS NULL OR d.next_attempt_at <= ?)
122 ORDER BY d.id LIMIT ?`, fmtTime(time.Now()), limit) 122 ORDER BY d.id LIMIT ?`, fmtTime(time.Now()), limit)
123 if err != nil { 123}
124 return nil, err 124
125// scanDelivery reads a due delivery and opens its hook's secret.
126func (s *Store) scanDelivery(row interface{ Scan(...any) error }) (Delivery, error) {
127 var d Delivery
128 if err := row.Scan(&d.ID, &d.WebhookID, &d.URL, &d.Secret, &d.EventID, &d.EventKind,
129 &d.RepoPath, &d.Actor, &d.DataJSON, &d.EventAt, &d.Attempts); err != nil {
130 return d, err
125 } 131 }
126 defer rows.Close() 132 secret, err := s.openValue(webhookAAD(d.WebhookID), d.Secret)
127 var out []Delivery 133 if err != nil {
128 for rows.Next() { 134 return d, fmt.Errorf("webhook %d: %w", d.WebhookID, err)
129 var d Delivery
130 if err := rows.Scan(&d.ID, &d.WebhookID, &d.URL, &d.Secret, &d.EventID, &d.EventKind,
131 &d.RepoPath, &d.Actor, &d.DataJSON, &d.EventAt, &d.Attempts); err != nil {
132 return nil, err
133 }
134 if d.Secret, err = s.openValue(webhookAAD(d.WebhookID), d.Secret); err != nil {
135 return nil, fmt.Errorf("webhook %d: %w", d.WebhookID, err)
136 }
137 out = append(out, d)
138 } 135 }
139 return out, rows.Err() 136 d.Secret = secret
137 return d, nil
140} 138}
141 139
142func (s *Store) MarkDelivered(id int64, status int) error { 140func (s *Store) MarkDelivered(id int64, status int) error {
@@ -161,7 +159,7 @@ func (s *Store) MarkAttemptFailed(id int64, status int, errMsg string, nextAt *t
161} 159}
162 160
163func (s *Store) ListDeliveries(repoID int64, limit int) ([]DeliveryStatus, error) { 161func (s *Store) ListDeliveries(repoID int64, limit int) ([]DeliveryStatus, error) {
164 rows, err := s.DB.Query(` 162 return queryAll(s.DB, scanDeliveryStatus, `
165 SELECT d.id, w.url, e.kind, 163 SELECT d.id, w.url, e.kind,
166 CASE WHEN d.delivered_at IS NOT NULL THEN 'delivered' 164 CASE WHEN d.delivered_at IS NOT NULL THEN 'delivered'
167 WHEN d.failed_at IS NOT NULL THEN 'failed' 165 WHEN d.failed_at IS NOT NULL THEN 'failed'
@@ -171,19 +169,6 @@ func (s *Store) ListDeliveries(repoID int64, limit int) ([]DeliveryStatus, error
171 JOIN webhooks w ON w.id = d.webhook_id 169 JOIN webhooks w ON w.id = d.webhook_id
172 JOIN events e ON e.id = d.event_id 170 JOIN events e ON e.id = d.event_id
173 WHERE w.repo_id = ? ORDER BY d.id DESC LIMIT ?`, repoID, limit) 171 WHERE w.repo_id = ? ORDER BY d.id DESC LIMIT ?`, repoID, limit)
174 if err != nil {
175 return nil, err
176 }
177 defer rows.Close()
178 var out []DeliveryStatus
179 for rows.Next() {
180 var d DeliveryStatus
181 if err := rows.Scan(&d.ID, &d.URL, &d.EventKind, &d.Status, &d.Attempts, &d.LastStatus, &d.LastError, &d.CreatedAt); err != nil {
182 return nil, err
183 }
184 out = append(out, d)
185 }
186 return out, rows.Err()
187} 172}
188 173
189// Redeliver resets a delivery for an immediate retry. 174// Redeliver resets a delivery for an immediate retry.
@@ -199,3 +184,9 @@ func (s *Store) Redeliver(repoID, deliveryID int64) error {
199 } 184 }
200 return nil 185 return nil
201} 186}
187
188func scanDeliveryStatus(row interface{ Scan(...any) error }) (DeliveryStatus, error) {
189 var d DeliveryStatus
190 err := row.Scan(&d.ID, &d.URL, &d.EventKind, &d.Status, &d.Attempts, &d.LastStatus, &d.LastError, &d.CreatedAt)
191 return d, err
192}
internal/webhook/webhook.go +5 −2
@@ -69,8 +69,11 @@ func CheckAddrs(host string, ips []net.IP, allowLocal bool) error {
69var cgnat = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)} 69var cgnat = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}
70 70
71func isForbidden(ip net.IP) bool { 71func isForbidden(ip net.IP) bool {
72 return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || 72 switch {
73 ip.IsMulticast() || ip.IsUnspecified() || cgnat.Contains(ip) 73 case ip.IsLoopback(), ip.IsPrivate(), ip.IsLinkLocalUnicast(), ip.IsMulticast(), ip.IsUnspecified():
74 return true
75 }
76 return cgnat.Contains(ip)
74} 77}
75 78
76type Deliverer struct { 79type Deliverer struct {