internal/deps/worker.go

223 lines · 6583 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, dir, sha, 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
123// checkAdvisories matches the resolved set against OSV. A Go advisory that
124// names packages counts only if a Go file at sha imports one of them; the
125// files are read only when such an advisory matched.
126func (w *Worker) checkAdvisories(ctx context.Context, repo store.Repo, dir, sha string, resolved []Dep) error {
127	if len(resolved) == 0 {
128		return w.reconcileAdvisories(repo, nil)
129	}
130	matched, err := w.Client.Advisories(ctx, resolved)
131	if err != nil {
132		return fmt.Errorf("advisories: %w", err)
133	}
134	for _, a := range matched {
135		if a.Ecosystem == EcoGo && len(a.Imports) > 0 {
136			if imported, ok := GoImports(ctx, dir, sha); ok {
137				MarkNotImported(matched, imported)
138			}
139			break
140		}
141	}
142	return w.reconcileAdvisories(repo, matched)
143}
144
145// behind queries the registries and keeps the dependencies whose latest
146// release is greater than what the manifest declares. A lookup that fails
147// is dropped rather than failing the sweep: one unreachable package should
148// not silence the rest, and the next sweep tries again.
149func (w *Worker) behind(ctx context.Context, found []Dep) ([]store.DepReport, error) {
150	var (
151		mu      sync.Mutex
152		out     []store.DepReport
153		errs    []string
154		wg      sync.WaitGroup
155		tickets = make(chan struct{}, lookups)
156	)
157	for _, d := range found {
158		wg.Add(1)
159		go func(d Dep) {
160			defer wg.Done()
161			tickets <- struct{}{}
162			defer func() { <-tickets }()
163			latest, err := w.Client.Latest(ctx, d.Ecosystem, d.Name)
164			mu.Lock()
165			defer mu.Unlock()
166			switch {
167			case err != nil:
168				errs = append(errs, fmt.Sprintf("%s %s: %v", d.Ecosystem, d.Name, err))
169			case latest != "" && Newer(d.Current, latest):
170				out = append(out, store.DepReport{
171					Ecosystem: d.Ecosystem, Name: d.Name, Current: d.Current, Latest: latest})
172			}
173		}(d)
174	}
175	wg.Wait()
176	if ctx.Err() != nil {
177		return nil, ctx.Err()
178	}
179	// Every lookup failing means the registries are unreachable, which is
180	// worth recording; a few failing is ordinary.
181	if len(errs) == len(found) && len(errs) > 0 {
182		return nil, errors.New(errs[0])
183	}
184	sort.Slice(out, func(i, j int) bool {
185		if out[i].Ecosystem != out[j].Ecosystem {
186			return out[i].Ecosystem < out[j].Ecosystem
187		}
188		return out[i].Name < out[j].Name
189	})
190	return out, nil
191}
192
193// reconcile brings the updates issue in line with what is behind.
194func (w *Worker) reconcile(repo store.Repo, behind []store.DepReport) error {
195	check, err := w.St.DepCheckFor(repo.ID)
196	if err != nil {
197		return err
198	}
199	previous, err := w.St.ReportedDeps(repo.ID)
200	if err != nil {
201		return err
202	}
203	return botissue.Maintain(w.St, w.Cfg, repo, botissue.Tracked{
204		Title:   IssueTitle,
205		Number:  check.IssueNumber,
206		Record:  func(n int64) error { return w.St.SetDepIssue(repo.ID, n) },
207		Empty:   len(behind) == 0,
208		Changed: !same(previous, behind),
209		Save:    func() error { return w.St.ReplaceDepReports(repo.ID, behind) },
210		Body:    func() string { return Body(repo.DefaultBranch, behind) },
211	})
212}
213
214// reconcileAdvisories brings the advisories issue in line with what
215// matches.
216func (w *Worker) reconcileAdvisories(repo store.Repo, matched []store.DepAdvisory) error {
217	previous, err := w.St.ReportedAdvisories(repo.ID)
218	if err != nil {
219		return err
220	}
221	return MaintainAdvisories(w.St, w.Cfg, repo, matched, !sameAdvisories(previous, matched),
222		func() error { return w.St.ReplaceDepAdvisories(repo.ID, matched) })
223}