internal/deps/worker.go

223 lines · 6518 bytes

  1package deps
  2
  3import (
  4	"context"
  5	"errors"
  6	"fmt"
  7	"log/slog"
  8	"os"
  9	"sort"
 10	"sync"
 11	"time"
 12
 13	"gitbay.org/gitbay/internal/botissue"
 14	"gitbay.org/gitbay/internal/config"
 15	"gitbay.org/gitbay/internal/gitutil"
 16	"gitbay.org/gitbay/internal/store"
 17)
 18
 19// manifestLimit bounds one manifest read out of the object store.
 20const manifestLimit = 1 << 20
 21
 22// lookups is how many registry requests one repository has in flight.
 23const lookups = 4
 24
 25// Worker sweeps repositories that have opted in, comparing their manifests
 26// against the registries and OSV and maintaining up to two issues per
 27// repository: one for updates, one for advisories.
 28type Worker struct {
 29	St      *store.Store
 30	Cfg     config.Config
 31	RepoDir func(owner, name string) string
 32	Client  *Client
 33	Tick    time.Duration
 34}
 35
 36func New(st *store.Store, cfg config.Config, repoDir func(owner, name string) string, version string) *Worker {
 37	tick := time.Hour
 38	if v := os.Getenv("GITBAY_DEPS_TICK"); v != "" {
 39		if d, err := time.ParseDuration(v); err == nil {
 40			tick = d
 41		}
 42	}
 43	return &Worker{St: st, Cfg: cfg, RepoDir: repoDir, Client: NewClient(version), Tick: tick}
 44}
 45
 46// Run sweeps until ctx ends.
 47func (w *Worker) Run(ctx context.Context) {
 48	t := time.NewTicker(w.Tick)
 49	defer t.Stop()
 50	for {
 51		select {
 52		case <-ctx.Done():
 53			return
 54		case <-t.C:
 55			w.Sweep(ctx)
 56		}
 57	}
 58}
 59
 60// Sweep checks every repository whose interval has elapsed. Split from the
 61// ticker for tests.
 62func (w *Worker) Sweep(ctx context.Context) {
 63	interval := w.Cfg.Deps.CheckIntervalHours
 64	if interval <= 0 {
 65		interval = 24
 66	}
 67	due, err := w.St.DueDepChecks(interval * 3600)
 68	if err != nil {
 69		slog.Error("deps: listing due repos", "err", err)
 70		return
 71	}
 72	for _, repo := range due {
 73		if ctx.Err() != nil {
 74			return
 75		}
 76		msg := ""
 77		if err := w.check(ctx, repo); err != nil {
 78			slog.Warn("deps check failed", "repo", repo.Path(), "err", err)
 79			msg = err.Error()
 80		}
 81		// Stamped either way, so a repo that fails every time is retried on
 82		// the interval rather than on every sweep.
 83		w.St.SetDepCheckResult(repo.ID, msg)
 84	}
 85}
 86
 87// check compares one repository against the registries and OSV, and
 88// reconciles its two issues with the result. A failure on one side leaves
 89// the other reconciled, and leaves its own issue as it was rather than
 90// closing it on an answer that never came.
 91func (w *Worker) check(ctx context.Context, repo store.Repo) error {
 92	dir := w.RepoDir(repo.OwnerName, repo.Name)
 93	sha, err := gitutil.ResolveRef(dir, "refs/heads/"+repo.DefaultBranch)
 94	if err != nil {
 95		return nil // empty repo, or no default branch yet
 96	}
 97	read := func(path string) ([]byte, error) {
 98		return gitutil.ReadBlob(dir, sha, path, manifestLimit)
 99	}
100	var root []string
101	if entries, err := gitutil.ListTree(dir, sha, ""); err == nil {
102		for _, e := range entries {
103			root = append(root, e.Name)
104		}
105	}
106	return errors.Join(
107		w.checkUpdates(ctx, repo, Scan(read)),
108		w.checkAdvisories(ctx, repo, Resolved(read, root)),
109	)
110}
111
112func (w *Worker) checkUpdates(ctx context.Context, repo store.Repo, found []Dep) error {
113	if len(found) == 0 {
114		return w.reconcile(repo, nil)
115	}
116	behind, err := w.behind(ctx, found)
117	if err != nil {
118		return err
119	}
120	return w.reconcile(repo, behind)
121}
122
123func (w *Worker) checkAdvisories(ctx context.Context, repo store.Repo, resolved []Dep) error {
124	if len(resolved) == 0 {
125		return w.reconcileAdvisories(repo, nil)
126	}
127	matched, err := w.Client.Advisories(ctx, resolved)
128	if err != nil {
129		return fmt.Errorf("advisories: %w", err)
130	}
131	return w.reconcileAdvisories(repo, matched)
132}
133
134// behind queries the registries and keeps the dependencies whose latest
135// release is greater than what the manifest declares. A lookup that fails
136// is dropped rather than failing the sweep: one unreachable package should
137// not silence the rest, and the next sweep tries again.
138func (w *Worker) behind(ctx context.Context, found []Dep) ([]store.DepReport, error) {
139	var (
140		mu      sync.Mutex
141		out     []store.DepReport
142		errs    []string
143		wg      sync.WaitGroup
144		tickets = make(chan struct{}, lookups)
145	)
146	for _, d := range found {
147		wg.Add(1)
148		go func(d Dep) {
149			defer wg.Done()
150			tickets <- struct{}{}
151			defer func() { <-tickets }()
152			latest, err := w.Client.Latest(ctx, d.Ecosystem, d.Name)
153			mu.Lock()
154			defer mu.Unlock()
155			switch {
156			case err != nil:
157				errs = append(errs, fmt.Sprintf("%s %s: %v", d.Ecosystem, d.Name, err))
158			case latest != "" && Newer(d.Current, latest):
159				out = append(out, store.DepReport{
160					Ecosystem: d.Ecosystem, Name: d.Name, Current: d.Current, Latest: latest})
161			}
162		}(d)
163	}
164	wg.Wait()
165	if ctx.Err() != nil {
166		return nil, ctx.Err()
167	}
168	// Every lookup failing means the registries are unreachable, which is
169	// worth recording; a few failing is ordinary.
170	if len(errs) == len(found) && len(errs) > 0 {
171		return nil, errors.New(errs[0])
172	}
173	sort.Slice(out, func(i, j int) bool {
174		if out[i].Ecosystem != out[j].Ecosystem {
175			return out[i].Ecosystem < out[j].Ecosystem
176		}
177		return out[i].Name < out[j].Name
178	})
179	return out, nil
180}
181
182// reconcile brings the updates issue in line with what is behind.
183func (w *Worker) reconcile(repo store.Repo, behind []store.DepReport) error {
184	check, err := w.St.DepCheckFor(repo.ID)
185	if err != nil {
186		return err
187	}
188	previous, err := w.St.ReportedDeps(repo.ID)
189	if err != nil {
190		return err
191	}
192	return botissue.Maintain(w.St, w.Cfg, repo, botissue.Tracked{
193		Title:   IssueTitle,
194		Number:  check.IssueNumber,
195		Record:  func(n int64) error { return w.St.SetDepIssue(repo.ID, n) },
196		Empty:   len(behind) == 0,
197		Changed: !same(previous, behind),
198		Save:    func() error { return w.St.ReplaceDepReports(repo.ID, behind) },
199		Body:    func() string { return Body(repo.DefaultBranch, behind) },
200	})
201}
202
203// reconcileAdvisories brings the advisories issue in line with what
204// matches.
205func (w *Worker) reconcileAdvisories(repo store.Repo, matched []store.DepAdvisory) error {
206	check, err := w.St.DepCheckFor(repo.ID)
207	if err != nil {
208		return err
209	}
210	previous, err := w.St.ReportedAdvisories(repo.ID)
211	if err != nil {
212		return err
213	}
214	return botissue.Maintain(w.St, w.Cfg, repo, botissue.Tracked{
215		Title:   AdvisoryTitle,
216		Number:  check.AdvisoryIssueNumber,
217		Record:  func(n int64) error { return w.St.SetDepAdvisoryIssue(repo.ID, n) },
218		Empty:   len(matched) == 0,
219		Changed: !sameAdvisories(previous, matched),
220		Save:    func() error { return w.St.ReplaceDepAdvisories(repo.ID, matched) },
221		Body:    func() string { return AdvisoryBody(repo.DefaultBranch, matched) },
222	})
223}