gunk-dev/the-valley

takeover.go

sourced9f7bacd171bmain's published tip history
6.2 KiB
1package cmd
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "slices"
11 "strings"
12 "syscall"
13 "time"
14
15 "the-valley/flow/internal/git"
16 "the-valley/flow/internal/integration"
17 "the-valley/flow/internal/run"
18)
19
20// continuationLockWait is how long a launch that continues a branch waits
21// for another such launch in the same clone to register its run.
22var continuationLockWait = 5 * time.Minute
23
24// lockContinuation takes the lock that serialises the launches continuing a
25// branch (--pr, --change, or --resume-from on its run's branch) in the
26// clone at repoRoot, from the check that no other run holds the branch or
27// the change through the new run's registration: a second launch waits,
28// then finds the first run registered and refuses. It waits up to
29// continuationLockWait, saying so on stderr. The returned func releases it.
30func lockContinuation(ctx context.Context, repoRoot string) (func(), error) {
31 f, err := openContinuationLock(ctx, repoRoot)
32 if err != nil {
33 return nil, err
34 }
35 deadline := time.Now().Add(continuationLockWait)
36 for said := false; ; said = true {
37 err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
38 if err == nil {
39 return func() { f.Close() }, nil // close drops the flock
40 }
41 if !errors.Is(err, syscall.EWOULDBLOCK) {
42 f.Close()
43 return nil, fmt.Errorf("locking %s: %w", f.Name(), err)
44 }
45 if !said {
46 fmt.Fprintf(os.Stderr, "waiting for another launch continuing a branch in %s to start its run...\n", repoRoot)
47 }
48 if time.Now().After(deadline) {
49 f.Close()
50 return nil, fmt.Errorf("another launch continuing a branch in %s still hasn't started its run after %s", repoRoot, continuationLockWait)
51 }
52 select {
53 case <-ctx.Done():
54 f.Close()
55 return nil, ctx.Err()
56 case <-time.After(200 * time.Millisecond):
57 }
58 }
59}
60
61// tryLockContinuation takes the lock lockContinuation takes, if no launch
62// holds it; ok is false when one does, or the lock can't be taken.
63func tryLockContinuation(ctx context.Context, repoRoot string) (release func(), ok bool) {
64 f, err := openContinuationLock(ctx, repoRoot)
65 if err != nil {
66 return nil, false
67 }
68 if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
69 f.Close()
70 return nil, false
71 }
72 return func() { f.Close() }, true
73}
74
75// openContinuationLock opens the continuation lock's file, in the clone's
76// common git directory, which its worktrees share.
77func openContinuationLock(ctx context.Context, repoRoot string) (*os.File, error) {
78 out, err := exec.CommandContext(ctx, "git", "-C", repoRoot, "rev-parse", "--git-common-dir").Output()
79 if err != nil {
80 return nil, fmt.Errorf("finding the git directory of %s: %w", repoRoot, err)
81 }
82 dir := strings.TrimSpace(string(out))
83 if !filepath.IsAbs(dir) {
84 dir = filepath.Join(repoRoot, dir)
85 }
86 return os.OpenFile(filepath.Join(dir, "klaus-continue.lock"), os.O_CREATE|os.O_RDWR, 0o644)
87}
88
89// occupantError is the refusal to create a worktree on branch while the
90// worktree at path has it checked out, holding work that origin lacks (""
91// for none): owner is the run that registered it, or nil when none did.
92// klaus never removes such a worktree, even for --force-takeover, so the
93// operator frees the branch first.
94func occupantError(branch, path, work string, owner *run.State) error {
95 what := path
96 if work != "" {
97 what += " (with " + work + ")"
98 }
99 if owner == nil {
100 return fmt.Errorf("branch %s is checked out in %s, which no klaus run registered; klaus never removes it: check another branch out there, or remove it yourself", branch, what)
101 }
102 free := "clean that run up first"
103 if work != "" {
104 free = "save that work, then clean that run up"
105 }
106 return fmt.Errorf("branch %s is checked out in run %s's worktree %s; klaus never removes a worktree, even with --force-takeover: %s (klaus cleanup %s, with --force while its agent runs) and launch again", branch, owner.ID, what, free, owner.ID)
107}
108
109// worktreeOwner returns the run whose recorded worktree is path, or nil.
110func worktreeOwner(states []*run.State, path string) *run.State {
111 clean := filepath.Clean(path)
112 for _, s := range states {
113 if s.Type != "session" && s.Worktree != "" && filepath.Clean(s.Worktree) == clean {
114 return s
115 }
116 }
117 return nil
118}
119
120// takeoverCandidates are the runs whose attention a run of changeID in repo
121// (as integration.RepoName names it) could take on: other runs of the
122// change that need attention and pushed their work, and that self doesn't
123// already record.
124func takeoverCandidates(states []*run.State, self *run.State, changeID string, repos ...string) []*run.State {
125 var out []*run.State
126 for _, s := range states {
127 if s.Type == "session" || s.ID == self.ID || s.ChangeID != changeID || !run.ValidChangeID(changeID) ||
128 !slices.Contains(repos, integration.RepoName(s)) || !needsAttention(s) || s.PushedSHA == nil ||
129 slices.Contains(self.TookOver, s.ID) {
130 continue
131 }
132 out = append(out, s)
133 }
134 return out
135}
136
137// recordTakeovers adds to self.TookOver each candidate whose pushed head is
138// head or one of its ancestors in the repo at dir: self holds that work.
139// It returns the IDs it added.
140func recordTakeovers(ctx context.Context, dir, head string, self *run.State, candidates []*run.State) []string {
141 var added []string
142 for _, s := range candidates {
143 if git.IsAncestor(ctx, dir, *s.PushedSHA, head) {
144 self.TookOver = append(self.TookOver, s.ID)
145 added = append(added, s.ID)
146 }
147 }
148 return added
149}
150
151// recordFinalTakeovers records, as a run finalizes, the runs of its change
152// that need attention and whose pushed heads the head it left on origin
153// contains: its pushed head, or for a PR its branch's tip on origin. It
154// asks origin only when there is such a run to check.
155func recordFinalTakeovers(ctx context.Context, gc git.Client, state *run.State) {
156 if state.Worktree == "" {
157 return
158 }
159 states, _ := run.ListAllSessions()
160 candidates := takeoverCandidates(states, state, state.ChangeID, integration.RepoName(state))
161 if len(candidates) == 0 {
162 return
163 }
164 var head string
165 switch {
166 case state.PushedSHA != nil:
167 head = *state.PushedSHA
168 case state.PRURL != nil && *state.PRURL != "":
169 head, _ = gc.RemoteBranchSHA(ctx, state.Worktree, state.Branch)
170 }
171 if head != "" {
172 recordTakeovers(ctx, state.Worktree, head, state, candidates)
173 }
174}