gunk-dev/the-valley

git_checker.go

source601b054bc28emain's published tip history
16.9 KiB
1package integration
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "log/slog"
9 "os"
10 "os/exec"
11 "strconv"
12 "strings"
13 "sync"
14 "syscall"
15 "time"
16
17 "the-valley/flow/internal/run"
18)
19
20const (
21 // remoteTimeout bounds ls-remote and fetch.
22 remoteTimeout = time.Minute
23 // localTimeout bounds each local git command.
24 localTimeout = time.Minute
25 // maxLandedScan bounds how many first-parent commits of the default
26 // branch the content check compares against.
27 maxLandedScan = 500
28)
29
30// GitChecker checks integration with git, in each run's own clone
31// (run.State.CloneDir). Per repo and per check it takes one snapshot of
32// origin with ls-remote, fetches only the default branch and the pushed
33// branches that still exist, and then judges each run:
34//
35// 1. Integrated: the pushed SHA, or the branch's current tip (the operator
36// may have rebased and force-pushed it), is an ancestor of the default
37// branch.
38// 2. IntegratedContent: a first-parent commit on the default branch,
39// committed after the run was created, has the same patch-id as the
40// branch's change (its diff from the merge base with the default branch).
41// This catches an integrator that lands a change as one new commit on top
42// of the default branch.
43// 3. Gone: the branch is no longer on origin, neither check matched, and
44// the evidence was complete: the pushed SHA is in the clone, shares
45// history with the default branch, and its change was compared against
46// every commit landed since the run was created.
47// 4. Awaiting: the branch is still on origin and neither check matched.
48//
49// A run without a clone, or whose origin can't be listed or fetched, is
50// Unknown, and so is a deleted branch whose evidence was incomplete (the
51// pushed SHA was pruned, the clone is shallow, or the scan of landed commits
52// hit its cap): an incomplete check never says Gone.
53//
54// Verdicts other than Unknown are cached in memory by what they were computed
55// from (the run, its clone, branch, pushed SHA and creation time, and origin's
56// default and branch tips), so a check whose tips haven't moved costs one
57// ls-remote per repo. A GitChecker is safe for concurrent use.
58type GitChecker struct {
59 logger *slog.Logger
60 // scanLimit bounds the walk of the default branch (maxLandedScan).
61 scanLimit int
62
63 mu sync.Mutex
64 verdicts map[cacheKey]Verdict
65 patchIDs map[string]string // default-branch commit SHA -> patch-id ("" when it has no diff)
66}
67
68// cacheKey is what a verdict was computed from.
69type cacheKey struct {
70 runID, cloneDir, pushedBranch, pushedSHA, createdAt, defaultTip, branchTip string
71}
72
73// NewGitChecker returns a GitChecker that logs incomplete checks at debug
74// level to logger (slog.Default when nil).
75func NewGitChecker(logger *slog.Logger) *GitChecker {
76 if logger == nil {
77 logger = slog.Default()
78 }
79 return &GitChecker{
80 logger: logger,
81 scanLimit: maxLandedScan,
82 verdicts: make(map[cacheKey]Verdict),
83 patchIDs: make(map[string]string),
84 }
85}
86
87// Check returns a verdict for every run that Applies. Runs are grouped by
88// clone so each repo is snapshotted once. Git knows nothing of changes.
89func (c *GitChecker) Check(ctx context.Context, runs []*run.State) Report {
90 return Report{Runs: c.judge(ctx, runs)}
91}
92
93func (c *GitChecker) judge(ctx context.Context, runs []*run.State) map[string]Result {
94 verdicts := c.judgeAll(ctx, runs)
95 out := make(map[string]Result, len(verdicts))
96 for id, v := range verdicts {
97 out[id] = Result{Verdict: v}
98 }
99 return out
100}
101
102func (c *GitChecker) judgeAll(ctx context.Context, runs []*run.State) map[string]Verdict {
103 c.mu.Lock()
104 defer c.mu.Unlock()
105
106 out := make(map[string]Verdict)
107 byDir := make(map[string][]*run.State)
108 var dirs []string
109 for _, s := range runs {
110 if !Applies(s) {
111 continue
112 }
113 if s.CloneDir == nil || *s.CloneDir == "" {
114 out[s.ID] = Unknown
115 c.logger.Debug("integration check: run has no clone", "run", s.ID)
116 continue
117 }
118 dir := *s.CloneDir
119 if _, ok := byDir[dir]; !ok {
120 dirs = append(dirs, dir)
121 }
122 byDir[dir] = append(byDir[dir], s)
123 }
124
125 // Keep only what this check used, so the caches don't grow without bound.
126 next := &checkCache{verdicts: make(map[cacheKey]Verdict), patchIDs: make(map[string]string)}
127 for _, dir := range dirs {
128 c.checkRepo(ctx, dir, byDir[dir], out, next)
129 }
130 c.verdicts, c.patchIDs = next.verdicts, next.patchIDs
131 return out
132}
133
134// checkCache collects the cache entries a check used.
135type checkCache struct {
136 verdicts map[cacheKey]Verdict
137 patchIDs map[string]string
138}
139
140// checkRepo judges the runs whose clone is dir.
141func (c *GitChecker) checkRepo(ctx context.Context, dir string, runs []*run.State, out map[string]Verdict, next *checkCache) {
142 unknown := func(rs []*run.State, err error) {
143 for _, s := range rs {
144 out[s.ID] = Unknown
145 }
146 c.logger.Debug("integration check incomplete", "clone", dir, "runs", len(rs), "err", err)
147 }
148 if fi, err := os.Stat(dir); err != nil || !fi.IsDir() {
149 if err == nil {
150 err = fmt.Errorf("not a directory")
151 }
152 unknown(runs, err)
153 return
154 }
155
156 snap, err := snapshotOrigin(ctx, dir)
157 if err != nil {
158 unknown(runs, err)
159 return
160 }
161
162 keys := make(map[string]cacheKey, len(runs))
163 var pending []*run.State
164 for _, s := range runs {
165 key := cacheKey{s.ID, dir, *s.PushedBranch, *s.PushedSHA, s.CreatedAt, snap.defaultTip, snap.heads[*s.PushedBranch]}
166 keys[s.ID] = key
167 if v, ok := c.verdicts[key]; ok {
168 out[s.ID] = v
169 next.verdicts[key] = v
170 continue
171 }
172 pending = append(pending, s)
173 }
174 if len(pending) == 0 {
175 return
176 }
177
178 if err := fetchSnapshot(ctx, dir, snap, pending); err != nil {
179 unknown(pending, err)
180 return
181 }
182
183 // The default branch's recent commits are walked at most once per repo,
184 // back to the oldest pending run, and only if a content check needs them.
185 var landed []landedCommit
186 var truncated bool
187 var landedErr error
188 walked := false
189 landedFn := func() ([]landedCommit, bool, error) {
190 if !walked {
191 walked = true
192 landed, truncated, landedErr = c.landedCommits(ctx, dir, snap.defaultTip, oldestCreated(pending), next)
193 }
194 return landed, truncated, landedErr
195 }
196
197 for _, s := range pending {
198 v, err := judge(ctx, dir, snap, s, landedFn)
199 if err != nil {
200 unknown([]*run.State{s}, err)
201 continue
202 }
203 out[s.ID] = v
204 // Unknown is never cached: the next check may have what this one
205 // lacked.
206 if v != Unknown {
207 next.verdicts[keys[s.ID]] = v
208 }
209 }
210}
211
212// judge applies the verdicts, in order, to one run. landed returns the
213// default branch's recent commits and whether the walk was cut short by the
214// cap.
215func judge(ctx context.Context, dir string, snap snapshot, s *run.State, landed func() ([]landedCommit, bool, error)) (Verdict, error) {
216 pushed := *s.PushedSHA
217 tip := snap.heads[*s.PushedBranch]
218 candidates := []string{pushed}
219 if tip != "" && tip != pushed {
220 candidates = append(candidates, tip)
221 }
222 // A candidate whose object isn't here after the fetch is skipped.
223 var local []string
224 for _, x := range candidates {
225 ok, err := hasObject(ctx, dir, x)
226 if err != nil {
227 return Unknown, err
228 }
229 if ok {
230 local = append(local, x)
231 }
232 }
233
234 for _, x := range local {
235 ok, err := isAncestor(ctx, dir, x, snap.defaultTip)
236 if err != nil {
237 return Unknown, err
238 }
239 if ok {
240 return Integrated, nil
241 }
242 }
243
244 // complete is set once a candidate's change could be compared: it is
245 // here and shares history with the default branch. Without that, a
246 // deleted branch is Unknown, not Gone.
247 complete := false
248 want := make(map[string]bool)
249 for _, x := range local {
250 id, ok, err := changePatchID(ctx, dir, snap.defaultTip, x)
251 if err != nil {
252 return Unknown, err
253 }
254 if !ok {
255 continue
256 }
257 complete = true
258 if id != "" {
259 want[id] = true
260 }
261 }
262 if len(want) > 0 {
263 commits, truncated, err := landed()
264 if err != nil {
265 return Unknown, err
266 }
267 since := createdAt(s)
268 for _, lc := range commits {
269 if lc.when.Before(since) {
270 continue
271 }
272 if lc.patchID != "" && want[lc.patchID] {
273 return IntegratedContent, nil
274 }
275 }
276 // A walk cut short by the cap covered this run only if it reached a
277 // commit from before the run was created.
278 if truncated && (since.IsZero() || len(commits) == 0 || !commits[len(commits)-1].when.Before(since)) {
279 complete = false
280 }
281 }
282
283 switch {
284 case tip != "":
285 return Awaiting, nil
286 case complete:
287 return Gone, nil
288 default:
289 return Unknown, nil
290 }
291}
292
293// snapshot is origin's default branch and branch tips at one moment.
294type snapshot struct {
295 defaultBranch string
296 defaultTip string
297 heads map[string]string // branch name -> tip SHA
298}
299
300// snapshotOrigin lists origin's HEAD and branches with one ls-remote.
301func snapshotOrigin(ctx context.Context, dir string) (snapshot, error) {
302 out, err := gitRun(ctx, dir, nil, remoteTimeout, "ls-remote", "--symref", "origin", "HEAD", "refs/heads/*")
303 if err != nil {
304 return snapshot{}, err
305 }
306 snap := snapshot{heads: make(map[string]string)}
307 for _, line := range strings.Split(string(out), "\n") {
308 left, ref, ok := strings.Cut(strings.TrimSpace(line), "\t")
309 if !ok {
310 continue
311 }
312 if target, isSym := strings.CutPrefix(left, "ref: "); isSym {
313 if ref == "HEAD" {
314 snap.defaultBranch = strings.TrimPrefix(target, "refs/heads/")
315 }
316 continue
317 }
318 if name, isHead := strings.CutPrefix(ref, "refs/heads/"); isHead {
319 snap.heads[name] = left
320 }
321 }
322 if snap.defaultBranch == "" {
323 // Some servers don't advertise HEAD's target; fall back to the
324 // clone's record of it.
325 if ref, err := gitRun(ctx, dir, nil, localTimeout, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"); err == nil {
326 snap.defaultBranch = strings.TrimPrefix(strings.TrimSpace(string(ref)), "refs/remotes/origin/")
327 }
328 }
329 if snap.defaultBranch == "" {
330 return snapshot{}, fmt.Errorf("origin's default branch is unknown")
331 }
332 snap.defaultTip = snap.heads[snap.defaultBranch]
333 if snap.defaultTip == "" {
334 return snapshot{}, fmt.Errorf("origin has no branch %q", snap.defaultBranch)
335 }
336 return snap, nil
337}
338
339// fetchSnapshot fetches the default branch and the runs' branches that are
340// still on origin, with explicit refspecs.
341func fetchSnapshot(ctx context.Context, dir string, snap snapshot, runs []*run.State) error {
342 refspec := func(b string) string { return "+refs/heads/" + b + ":refs/remotes/origin/" + b }
343 args := []string{"fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules",
344 "origin", refspec(snap.defaultBranch)}
345 seen := map[string]bool{snap.defaultBranch: true}
346 for _, s := range runs {
347 b := *s.PushedBranch
348 if snap.heads[b] == "" || seen[b] {
349 continue
350 }
351 seen[b] = true
352 args = append(args, refspec(b))
353 }
354 _, err := gitRun(ctx, dir, nil, remoteTimeout, args...)
355 return err
356}
357
358// landedCommit is a first-parent commit on the default branch.
359type landedCommit struct {
360 sha string
361 when time.Time // committer date
362 patchID string // "" for a merge or a commit with no diff
363}
364
365// landedCommits lists up to c.scanLimit first-parent commits of tip
366// committed since since (all of them when since is zero), newest first, with
367// their patch-ids. truncated reports that there were more: the walk stopped
368// at the cap, not at since. Patch-ids already computed are reused: commits
369// don't change.
370func (c *GitChecker) landedCommits(ctx context.Context, dir, tip string, since time.Time, next *checkCache) (commits []landedCommit, truncated bool, err error) {
371 // One commit past the cap tells a full walk from a cut-short one.
372 args := []string{"log", "--first-parent", "--format=%H %ct", "-n", strconv.Itoa(c.scanLimit + 1)}
373 if !since.IsZero() {
374 args = append(args, "--since="+strconv.FormatInt(since.Unix(), 10))
375 }
376 out, err := gitRun(ctx, dir, nil, localTimeout, append(args, tip)...)
377 if err != nil {
378 return nil, false, err
379 }
380 var lines []string
381 if s := strings.TrimSpace(string(out)); s != "" {
382 lines = strings.Split(s, "\n")
383 }
384 if len(lines) > c.scanLimit {
385 lines, truncated = lines[:c.scanLimit], true
386 }
387 var missing []string
388 for _, line := range lines {
389 sha, ct, ok := strings.Cut(line, " ")
390 if !ok {
391 continue
392 }
393 secs, err := strconv.ParseInt(ct, 10, 64)
394 if err != nil {
395 continue
396 }
397 commits = append(commits, landedCommit{sha: sha, when: time.Unix(secs, 0)})
398 if _, ok := c.patchIDs[sha]; !ok {
399 missing = append(missing, sha)
400 }
401 }
402 computed, err := commitPatchIDs(ctx, dir, missing)
403 if err != nil {
404 return nil, false, err
405 }
406 for i := range commits {
407 sha := commits[i].sha
408 id, ok := c.patchIDs[sha]
409 if !ok {
410 id = computed[sha]
411 }
412 commits[i].patchID = id
413 next.patchIDs[sha] = id
414 }
415 return commits, truncated, nil
416}
417
418// commitPatchIDs returns the patch-id of each commit's diff against its
419// parent. Commits without one (merges, empty commits) are absent.
420func commitPatchIDs(ctx context.Context, dir string, shas []string) (map[string]string, error) {
421 ids := make(map[string]string)
422 if len(shas) == 0 {
423 return ids, nil
424 }
425 diff, err := gitRun(ctx, dir, []byte(strings.Join(shas, "\n")+"\n"), localTimeout, "diff-tree", "--stdin", "-r", "-p")
426 if err != nil {
427 return nil, err
428 }
429 if len(diff) == 0 {
430 return ids, nil
431 }
432 out, err := gitRun(ctx, dir, diff, localTimeout, "patch-id", "--stable")
433 if err != nil {
434 return nil, err
435 }
436 for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
437 if f := strings.Fields(line); len(f) == 2 {
438 ids[f[1]] = f[0]
439 }
440 }
441 return ids, nil
442}
443
444// changePatchID returns the patch-id of x's change relative to base: the
445// diff from their merge base to x, "" when the change is empty. ok is false
446// when the clone has no merge base for them (unrelated or shallow history),
447// so the change can't be compared.
448func changePatchID(ctx context.Context, dir, base, x string) (id string, ok bool, err error) {
449 mb, err := gitRun(ctx, dir, nil, localTimeout, "merge-base", base, x)
450 if exitCode(err) == 1 {
451 return "", false, nil // no common ancestor
452 }
453 if err != nil {
454 return "", false, err
455 }
456 diff, err := gitRun(ctx, dir, nil, localTimeout, "diff-tree", "-r", "-p", strings.TrimSpace(string(mb)), x)
457 if err != nil {
458 return "", false, err
459 }
460 if len(diff) == 0 {
461 return "", true, nil
462 }
463 out, err := gitRun(ctx, dir, diff, localTimeout, "patch-id", "--stable")
464 if err != nil {
465 return "", false, err
466 }
467 if f := strings.Fields(string(out)); len(f) > 0 {
468 return f[0], true, nil
469 }
470 return "", true, nil
471}
472
473// hasObject reports whether the object named by a full SHA is in the clone.
474func hasObject(ctx context.Context, dir, sha string) (bool, error) {
475 _, err := gitRun(ctx, dir, nil, localTimeout, "cat-file", "-e", sha)
476 switch exitCode(err) {
477 case 0:
478 return true, nil
479 case 1:
480 return false, nil
481 }
482 return false, err
483}
484
485// isAncestor reports whether x is an ancestor of (or equal to) tip.
486func isAncestor(ctx context.Context, dir, x, tip string) (bool, error) {
487 _, err := gitRun(ctx, dir, nil, localTimeout, "merge-base", "--is-ancestor", x, tip)
488 switch exitCode(err) {
489 case 0:
490 return true, nil
491 case 1:
492 return false, nil
493 }
494 return false, err
495}
496
497// createdAt parses a run's creation time; zero when it can't.
498func createdAt(s *run.State) time.Time {
499 t, _ := time.Parse(time.RFC3339, s.CreatedAt)
500 return t
501}
502
503// oldestCreated returns the earliest creation time among runs, or zero when
504// any of them is unknown, so the walk covers every run.
505func oldestCreated(runs []*run.State) time.Time {
506 var oldest time.Time
507 for i, s := range runs {
508 t := createdAt(s)
509 if t.IsZero() {
510 return time.Time{}
511 }
512 if i == 0 || t.Before(oldest) {
513 oldest = t
514 }
515 }
516 return oldest
517}
518
519// gitError is a failed git command with its stderr.
520type gitError struct {
521 args []string
522 err error
523 stderr string
524}
525
526func (e *gitError) Error() string {
527 return fmt.Sprintf("git %s: %v: %s", strings.Join(e.args, " "), e.err, strings.TrimSpace(e.stderr))
528}
529
530func (e *gitError) Unwrap() error { return e.err }
531
532// exitCode returns the exit status of a failed git command: 0 for no error
533// and -1 when the command didn't run to an exit status (e.g. timed out).
534func exitCode(err error) int {
535 if err == nil {
536 return 0
537 }
538 var exitErr *exec.ExitError
539 if errors.As(err, &exitErr) && exitErr.ExitCode() > 0 {
540 return exitErr.ExitCode()
541 }
542 return -1
543}
544
545// gitRun runs git in dir and returns its stdout. It never prompts: git's
546// terminal prompt is off, and the command runs in a new session with no
547// controlling terminal, so ssh can't ask for a passphrase or host key on
548// the dashboard's screen either.
549func gitRun(ctx context.Context, dir string, stdin []byte, timeout time.Duration, args ...string) ([]byte, error) {
550 ctx, cancel := context.WithTimeout(ctx, timeout)
551 defer cancel()
552 cmd := exec.CommandContext(ctx, "git", args...)
553 cmd.Dir = dir
554 cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
555 cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
556 cmd.WaitDelay = 5 * time.Second
557 if stdin != nil {
558 cmd.Stdin = bytes.NewReader(stdin)
559 }
560 var stdout, stderr bytes.Buffer
561 cmd.Stdout = &stdout
562 cmd.Stderr = &stderr
563 if err := cmd.Run(); err != nil {
564 if ctx.Err() != nil {
565 err = fmt.Errorf("%w (%v)", ctx.Err(), err)
566 }
567 return nil, &gitError{args: args, err: err, stderr: stderr.String()}
568 }
569 return stdout.Bytes(), nil
570}