gunk-dev/the-valley

valley.go

sourcecfedff357a41main's published tip history
15.2 KiB
1// Package valley drives the `valley` CLI of a valley, the self-hosted
2// integration host that direct-push repos deliver to: marking a pushed head
3// ready as a version of its change, returning a change to draft, and reading
4// the valley's view of every change.
5package valley
6
7import (
8 "bytes"
9 "context"
10 "errors"
11 "fmt"
12 "log/slog"
13 "os"
14 "os/exec"
15 "regexp"
16 "slices"
17 "strconv"
18 "strings"
19 "sync"
20 "syscall"
21 "time"
22
23 "the-valley/flow/internal/git"
24)
25
26const (
27 // ReadyTimeout bounds `valley ready`.
28 ReadyTimeout = 30 * time.Second
29 // UnreadyTimeout bounds `valley unready`.
30 UnreadyTimeout = 30 * time.Second
31 // helpTimeout bounds `valley help`.
32 helpTimeout = 10 * time.Second
33 // gitTimeout bounds each git command detection runs.
34 gitTimeout = 30 * time.Second
35 // maxReason caps the length of a failure's reason.
36 maxReason = 200
37)
38
39// ListTimeout bounds `valley changes`. A listing of a large valley can take
40// more than a minute; it is a variable so tests can shorten it.
41var ListTimeout = 3 * time.Minute
42
43// Error is a valley command that failed: it refused (exited non-zero), timed
44// out, couldn't start, or printed something klaus can't read. Reason is
45// short enough to record on a run.
46type Error struct {
47 Verb string
48 Reason string
49 // Conflict is set when valley exited with status 3, a conflict: for a
50 // knot write, another write changed what it depends on.
51 Conflict bool
52 exited bool // valley ran and exited non-zero: Reason is its own message
53}
54
55func (e *Error) Error() string {
56 return "valley " + e.Verb + ": " + e.Reason
57}
58
59// Readied is what `valley ready` reports: the repo, the change's handle and
60// the version the head became.
61type Readied struct {
62 Repo string
63 Handle string
64 Version int
65}
66
67// readyLine is the line `valley ready` prints on success, e.g.
68// "site nxvp v2 ready".
69var readyLine = regexp.MustCompile(`^(\S+) (\S+) v(\d+) ready$`)
70
71// Ready runs `valley ready --change <changeID> --head <head> <branch>` in dir,
72// marking head ready as a version of the change. The valley identifies the
73// pusher from git config valley.principal, which the host sets, not klaus.
74func Ready(ctx context.Context, dir, changeID, head, branch string) (Readied, error) {
75 out, err := command(ctx, dir, ReadyTimeout, "ready", "--change", changeID, "--head", head, branch)
76 if err != nil {
77 return Readied{}, err
78 }
79 return parseReady(out)
80}
81
82func parseReady(out []byte) (Readied, error) {
83 for _, line := range strings.Split(string(out), "\n") {
84 m := readyLine.FindStringSubmatch(strings.TrimSpace(line))
85 if m == nil {
86 continue
87 }
88 if n, err := strconv.Atoi(m[3]); err == nil {
89 return Readied{Repo: m[1], Handle: m[2], Version: n}, nil
90 }
91 }
92 return Readied{}, &Error{Verb: "ready", Reason: "unexpected output: " + shortReason(out)}
93}
94
95// Unreadied is what `valley unready` reports. Draft is false when the
96// change wasn't ready (already a draft, or the valley has no record of it),
97// and Note then says what the valley printed.
98type Unreadied struct {
99 Repo string
100 Handle string
101 Draft bool
102 Note string
103}
104
105// draftLine is the line `valley unready` prints on success, e.g.
106// "site nxvp v1 draft", naming the version that was ready. A valley that
107// names no version prints "site nxvp draft".
108var draftLine = regexp.MustCompile(`^(\S+) (\S+)(?: v\d+)? draft$`)
109
110// notReady matches a message that only says the change wasn't ready to
111// begin with, which leaves it as unready asked. The valley exits 1 for this
112// refusal as for every other, so only its wording tells them apart: it says
113// "is a draft already; ready it to resume it".
114var notReady = regexp.MustCompile(`(?i)\bnot ready\b|\balready (a )?draft\b|\bdraft already\b|\bno (change )?record\b`)
115
116// Unready runs `valley unready <changeID>` in dir, returning a ready change
117// to draft so approve refuses it while an agent continues it. A change that
118// wasn't ready isn't an error, whether valley says so or refuses for that
119// reason: it is reported with Draft false. Any other output is an error,
120// since the change may still be approvable.
121func Unready(ctx context.Context, dir, changeID string) (Unreadied, error) {
122 out, err := command(ctx, dir, UnreadyTimeout, "unready", changeID)
123 var e *Error
124 if errors.As(err, &e) && e.exited && notReady.MatchString(e.Reason) {
125 return Unreadied{Note: e.Reason}, nil
126 }
127 if err != nil {
128 return Unreadied{}, err
129 }
130 return parseUnready(out)
131}
132
133func parseUnready(out []byte) (Unreadied, error) {
134 for _, line := range strings.Split(string(out), "\n") {
135 if m := draftLine.FindStringSubmatch(strings.TrimSpace(line)); m != nil {
136 return Unreadied{Repo: m[1], Handle: m[2], Draft: true}, nil
137 }
138 }
139 if msg := shortReason(out); notReady.MatchString(msg) {
140 return Unreadied{Note: msg}, nil
141 }
142 return Unreadied{}, &Error{Verb: "unready", Reason: "unexpected output: " + shortReason(out)}
143}
144
145// ChecksRefusalMemory is how long klaus remembers that the valley CLI refused
146// --checks before it tries the flag again; the CLI updates itself. It is a
147// variable so tests can shorten it.
148var ChecksRefusalMemory = 10 * time.Minute
149
150var checksRefused struct {
151 sync.Mutex
152 at time.Time
153 logged bool
154}
155
156// List runs `valley changes --all --json --checks` in dir: one process for
157// every repo the valley serves, with each ready change's checks.
158func List(ctx context.Context, dir string) (*Changes, error) {
159 return listChecks(ctx, dir, "changes", "--all", "--json")
160}
161
162// ListRepo runs `valley changes --json` in dir: the valley's view of the
163// repo in dir alone. It leaves out checks, which cost the host time to
164// compute; ListRepoChecks asks for them.
165func ListRepo(ctx context.Context, dir string) (*Changes, error) {
166 out, err := command(ctx, dir, ListTimeout, "changes", "--json")
167 if err != nil {
168 return nil, err
169 }
170 return Decode(out)
171}
172
173// ListRepoChecks is ListRepo with each ready change's checks.
174func ListRepoChecks(ctx context.Context, dir string) (*Changes, error) {
175 return listChecks(ctx, dir, "changes", "--json")
176}
177
178// listChecks runs the listing args with --checks. A CLI from before the flag
179// refuses it; klaus then lists without it, so the changes carry no checks,
180// and remembers the refusal for ChecksRefusalMemory. Any other failure is
181// returned as it is.
182func listChecks(ctx context.Context, dir string, args ...string) (*Changes, error) {
183 checksRefused.Lock()
184 skip := !checksRefused.at.IsZero() && time.Since(checksRefused.at) < ChecksRefusalMemory
185 checksRefused.Unlock()
186 if !skip {
187 out, err := command(ctx, dir, ListTimeout, append(slices.Clone(args), "--checks")...)
188 if err == nil {
189 return Decode(out)
190 }
191 var ve *Error
192 if !errors.As(err, &ve) || !ve.exited || !strings.Contains(ve.Reason, "--checks") {
193 return nil, err
194 }
195 checksRefused.Lock()
196 checksRefused.at = time.Now()
197 first := !checksRefused.logged
198 checksRefused.logged = true
199 checksRefused.Unlock()
200 if first {
201 slog.Info("valley changes does not take --checks; listing without it, so checks are not shown", "reason", ve.Reason)
202 }
203 }
204 out, err := command(ctx, dir, ListTimeout, args...)
205 if err != nil {
206 return nil, err
207 }
208 return Decode(out)
209}
210
211// changeVerbs are the verbs klaus needs to mark changes ready and read them.
212var changeVerbs = []string{"ready", "changes"}
213
214// Supported reports whether the valley on PATH has the verbs klaus uses: its
215// help lists both ready and changes. A valley from before change records
216// lacks them, and klaus treats its repos as plain direct-push repos.
217func Supported(ctx context.Context) bool {
218 return hasVerbs(ctx, changeVerbs...)
219}
220
221// HasUnready reports whether the valley on PATH lists unready, which a
222// valley from before drafts lacks.
223func HasUnready(ctx context.Context) bool {
224 return hasVerbs(ctx, "unready")
225}
226
227// hasVerbs reports whether the valley on PATH lists every one of verbs in
228// its help.
229func hasVerbs(ctx context.Context, verbs ...string) bool {
230 if _, err := exec.LookPath("valley"); err != nil {
231 return false
232 }
233 // Some CLIs exit non-zero from help; the listing is what counts.
234 stdout, stderr, _ := execValley(ctx, "", helpTimeout, nil, "help")
235 help := append(stdout, stderr...)
236 for _, v := range verbs {
237 if !hasVerb(help, v) {
238 return false
239 }
240 }
241 return true
242}
243
244// hasVerb reports whether help lists verb: a line that starts with it, after
245// at most a little indentation and an optional "usage: valley". Prose that
246// merely uses the word sits deeper in the text and doesn't count.
247func hasVerb(help []byte, verb string) bool {
248 re := regexp.MustCompile(`(?m)^[ \t]{0,4}(?:usage:[ \t]+)?(?:valley[ \t]+)?` + regexp.QuoteMeta(verb) + `\b`)
249 return re.Match(help)
250}
251
252// Detect reports whether the repo in dir delivers to a valley that klaus can
253// mark changes ready on: its origin isn't GitHub, the pushed head of branch
254// carries the valley's policy (HasPolicy), and the valley on PATH is
255// Supported. A head the repo lacks, as when a sandbox pushed it, is fetched
256// from origin first. The cheap checks come first, so a repo without the
257// policy never runs valley.
258func Detect(ctx context.Context, dir, branch, head string) bool {
259 return detect(ctx, dir, branch, head, changeVerbs...)
260}
261
262// DetectUnready is Detect for a launch that continues a change, with head
263// the commit its worktree starts from: it also requires the valley on PATH
264// to list unready, which a valley from before drafts lacks.
265func DetectUnready(ctx context.Context, dir, head string) bool {
266 return detect(ctx, dir, "", head, append(changeVerbs, "unready")...)
267}
268
269func detect(ctx context.Context, dir, branch, head string, verbs ...string) bool {
270 if dir == "" || head == "" {
271 return false
272 }
273 origin, err := gitOutput(ctx, dir, "remote", "get-url", "origin")
274 if err != nil || origin == "" || git.IsGitHubRemote(origin) {
275 return false
276 }
277 if _, err := gitOutput(ctx, dir, "cat-file", "-e", head+"^{commit}"); err != nil && branch != "" {
278 _, _ = gitOutput(ctx, dir, "fetch", "--quiet", "--no-tags", "origin",
279 "+refs/heads/"+branch+":refs/remotes/origin/"+branch)
280 }
281 return HasPolicy(ctx, dir, head) && hasVerbs(ctx, verbs...)
282}
283
284// HasPolicy reports whether commit head, in the repo at dir, carries
285// policy/valley or a policy/instance/ directory. A head the repo doesn't have
286// carries neither.
287func HasPolicy(ctx context.Context, dir, head string) bool {
288 out, err := gitOutput(ctx, dir, "ls-tree", head, "--", "policy/valley", "policy/instance")
289 if err != nil {
290 return false
291 }
292 for _, line := range strings.Split(out, "\n") {
293 meta, path, ok := strings.Cut(line, "\t")
294 if !ok {
295 continue
296 }
297 f := strings.Fields(meta) // mode, type, object
298 switch {
299 case path == "policy/valley":
300 return true
301 case path == "policy/instance" && len(f) == 3 && f[1] == "tree":
302 return true
303 }
304 }
305 return false
306}
307
308// Principal returns the name the valley knows the repo in dir's pusher by:
309// its git config valley.principal, which the host sets. "" when unset.
310func Principal(ctx context.Context, dir string) string {
311 p, err := gitOutput(ctx, dir, "config", "--get", "valley.principal")
312 if err != nil {
313 return ""
314 }
315 return p
316}
317
318// OriginRefs reads where each of refs is on the origin of the repo in dir,
319// with one ls-remote. A ref origin lacks is missing from the map.
320func OriginRefs(ctx context.Context, dir string, refs ...string) (map[string]string, error) {
321 out, err := gitOutput(ctx, dir, append([]string{"ls-remote", "origin"}, refs...)...)
322 if err != nil {
323 return nil, fmt.Errorf("reading origin's refs: %w", err)
324 }
325 want := make(map[string]bool, len(refs))
326 for _, r := range refs {
327 want[r] = true
328 }
329 got := make(map[string]string)
330 for _, line := range strings.Split(out, "\n") {
331 oid, ref, ok := strings.Cut(line, "\t")
332 if ok && want[ref] {
333 got[ref] = oid
334 }
335 }
336 return got, nil
337}
338
339// command runs valley and returns its stdout, or an *Error.
340func command(ctx context.Context, dir string, timeout time.Duration, args ...string) ([]byte, error) {
341 return commandInput(ctx, dir, timeout, nil, args...)
342}
343
344// commandInput is command with stdin, for a verb that reads it.
345func commandInput(ctx context.Context, dir string, timeout time.Duration, stdin []byte, args ...string) ([]byte, error) {
346 stdout, stderr, err := execValley(ctx, dir, timeout, stdin, args...)
347 if err == nil {
348 return stdout, nil
349 }
350 e := &Error{Verb: args[0]}
351 if args[0] == "knot" && len(args) > 1 {
352 e.Verb += " " + args[1]
353 }
354 var exitErr *exec.ExitError
355 switch {
356 case errors.Is(err, context.DeadlineExceeded):
357 e.Reason = fmt.Sprintf("timed out after %s", timeout)
358 case errors.As(err, &exitErr):
359 // A refusal: the valley's message, from stderr or else stdout.
360 e.exited = true
361 e.Conflict = exitErr.ExitCode() == 3
362 e.Reason = shortReason(stderr)
363 if e.Reason == "" {
364 e.Reason = shortReason(stdout)
365 }
366 if e.Reason == "" {
367 e.Reason = err.Error()
368 }
369 default:
370 e.Reason = err.Error()
371 }
372 return nil, e
373}
374
375// execValley runs valley in dir (the current directory when empty), with
376// stdin on its standard input. It never prompts: stdin is all valley reads,
377// git's terminal prompt is off, and the command runs in a new session with no
378// controlling terminal, so ssh can't ask for a passphrase on the dashboard's
379// screen. A timeout reports
380// context.DeadlineExceeded, and kills valley and everything it started.
381func execValley(ctx context.Context, dir string, timeout time.Duration, stdin []byte, args ...string) (stdout, stderr []byte, err error) {
382 ctx, cancel := context.WithTimeout(ctx, timeout)
383 defer cancel()
384 cmd := exec.CommandContext(ctx, "valley", args...)
385 cmd.Dir = dir
386 cmd.Env = append(cmd.Environ(), "GIT_TERMINAL_PROMPT=0") // Environ sets PWD to Dir
387 isolate(cmd)
388 var out, errOut bytes.Buffer
389 cmd.Stdin = bytes.NewReader(stdin)
390 cmd.Stdout, cmd.Stderr = &out, &errOut
391 err = cmd.Run()
392 if err != nil && ctx.Err() != nil {
393 err = ctx.Err()
394 }
395 return out.Bytes(), errOut.Bytes(), err
396}
397
398// shortReason joins a message's non-empty lines and caps its length.
399func shortReason(msg []byte) string {
400 var lines []string
401 for _, l := range strings.Split(string(msg), "\n") {
402 if l = strings.TrimSpace(l); l != "" {
403 lines = append(lines, l)
404 }
405 }
406 r := []rune(strings.Join(lines, "; "))
407 if len(r) > maxReason {
408 return string(r[:maxReason-1]) + "…"
409 }
410 return string(r)
411}
412
413// gitOutput runs git in dir and returns its trimmed stdout. Like valley, it
414// never prompts.
415func gitOutput(ctx context.Context, dir string, args ...string) (string, error) {
416 ctx, cancel := context.WithTimeout(ctx, gitTimeout)
417 defer cancel()
418 cmd := exec.CommandContext(ctx, "git", args...)
419 cmd.Dir = dir
420 cmd.Env = append(cmd.Environ(), "GIT_TERMINAL_PROMPT=0")
421 isolate(cmd)
422 out, err := cmd.Output()
423 return strings.TrimSpace(string(out)), err
424}
425
426// isolate runs cmd, made with exec.CommandContext, in a new session with no
427// controlling terminal. That makes cmd the leader of its own process group
428// (Setpgid on top would fail: a session leader can't change group), and when
429// the context ends the whole group is killed, so a child of cmd, such as the
430// ssh or git carrying out a ready, can't finish the work after klaus has
431// recorded that it timed out.
432func isolate(cmd *exec.Cmd) {
433 cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
434 cmd.Cancel = func() error {
435 err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
436 if errors.Is(err, syscall.ESRCH) {
437 return os.ErrProcessDone
438 }
439 return err
440 }
441 // Bounds the wait for output pipes held open by anything that left the
442 // group.
443 cmd.WaitDelay = 5 * time.Second
444}