gunk-dev/the-valley

approve.go

source01f84ae34d8amain's published tip history
45.3 KiB
1package main
2
3// approve files a change's integration request: the whole of `valley
4// approve`, which bin/valley hands to it, and review's [a]pprove
5// (review.go). Both run one attempt (approval.attempt), so the verb and
6// the key cannot drift apart.
7//
8// An attempt binds the head it files, derives what the policy at main's
9// tip requires of it (../derive), reuses the evidence origin already
10// holds for the head's tree (coverage.go), runs the rest in a throwaway
11// worktree through attest run, and files the request and the evidence in
12// one atomic push. attest run stores each note in this repository and
13// pushes nothing, so no evidence stands published for a change nobody has
14// approved, and the request is never filed without its evidence. Nothing
15// here writes the protected ref: the integrator judges the request and
16// lands it. Every way it ends is said in one verdict line
17// (verdict.go). With valley.telemetry on, each attempt is a telemetry run
18// of its own, recording approve.start, approve.policy, approve.coverage,
19// approve.checks, approve.request and approve.end, and attest records the
20// checks it runs under the linked run <run>-checks. A record is never
21// evidence, nothing reads one to decide anything, and a record that cannot
22// be stored costs that record alone.
23//
24// Review's [a]pprove is told the change review bound (reviewApproval), and
25// runs on review's own terminal. It leaves how the attempt ended in its
26// result, as fields:
27//
28// approved <change ID> <handle> <version> <head>
29// checks-failed <head>
30// refused
31// unknown
32// interrupted
33//
34// The approved result names what was filed, after the attempt's own reads
35// of the record, with empty fields for a plain branch. unknown is a
36// request whose state the attempt could not establish after the push.
37
38import (
39 "context"
40 "errors"
41 "fmt"
42 "io"
43 "os"
44 "os/exec"
45 "os/signal"
46 "regexp"
47 "sort"
48 "strconv"
49 "strings"
50 "sync"
51 "syscall"
52 "time"
53
54 "the-valley/derive"
55 "the-valley/telemetry"
56)
57
58const approveUsage = "usage: valley approve [-v] [--head <sha>] [--build-here] <change>"
59
60// interruptedStatus is the exit status of an approval cut short by a
61// signal, as a shell reports a process SIGINT ended.
62const interruptedStatus = 130
63
64// headArgument is the shape a --head value must have before it is read
65// as a commit: an object ID, or an abbreviation of one.
66var headArgument = regexp.MustCompile(`^[0-9a-f]{4,64}$`)
67
68// changeRequest is the request name of a change with a record, which no
69// branch is filed under.
70var changeRequest = regexp.MustCompile(`^c-[k-z]{32}$`)
71
72// approval is one approval attempt and what it was told.
73type approval struct {
74 g git
75 stdout, stderr io.Writer
76
77 verbose, buildHere bool
78 reviewing, carried bool
79 result []string // how the attempt ended, for review
80
81 // name is the change as it was named, read again before filing in case
82 // a plain branch has come to name a change. For a change, id, handle,
83 // version, head, branch, state and owner are what resolving that name
84 // read; head is the active version's head.
85 name string
86 id, handle, version, head, branch string
87 state, owner string
88 bound, boundVersion, title string // the head filed, its version and title
89 failedAt string // the head whose checks failed
90 filedID, filedHandle, filedVersion string // what the approved line names
91 tel *approveTelemetry
92 mu sync.Mutex
93 interrupted, finished bool
94 child *os.Process
95 childDone chan struct{}
96 worktree string
97 signals chan os.Signal
98}
99
100// errRefused is an attempt that ended without filing, having said why.
101var errRefused = errors.New("refused")
102
103// errUnknown is a request whose state could not be established after the
104// push, having said so.
105var errUnknown = errors.New("unknown")
106
107func runApprove(g git, args []string, stdout, stderr io.Writer) int {
108 a := &approval{g: g, stdout: stdout, stderr: stderr}
109 want, err := a.verbFlags(args)
110 if err != nil {
111 fmt.Fprintf(stderr, "valley: %s\n", err)
112 return 1
113 }
114 if !g.succeeds(true, "rev-parse", "--git-dir") {
115 fmt.Fprintln(stderr, "valley: not a git repository")
116 return 1
117 }
118 // The name is read before the fetch, as review reads it.
119 r, err := resolveRecorded(g, a.name)
120 if err != nil {
121 fmt.Fprintf(stderr, "valley: %s\n", err)
122 return 1
123 }
124 a.id, a.handle, a.head, a.branch, a.state, a.owner = r.id, r.handle, r.head, r.branch, r.state, r.owner
125 if r.id != "" {
126 a.version = strconv.Itoa(r.version)
127 }
128 fetch := exec.Command("git", "fetch", "--prune", "--quiet", "origin")
129 fetch.Env, fetch.Stdout, fetch.Stderr = g.env, stderr, stderr
130 processStarted()
131 if err := fetch.Run(); err != nil {
132 return exitCode(err)
133 }
134 a.watch(os.Interrupt, syscall.SIGTERM)
135 if a.id != "" {
136 if a.bindHead(want) != nil {
137 return 1
138 }
139 } else {
140 tip, ok, err := g.ref("refs/remotes/origin/" + a.branch)
141 if err != nil || !ok {
142 fmt.Fprintf(stderr, "valley: no such branch on origin: %s\n", a.branch)
143 return 1
144 }
145 if want != "" {
146 at, _ := g.output(true, "rev-parse", "--verify", "--quiet", want+"^{commit}")
147 if at != tip {
148 a.declined(fmt.Sprintf("origin/%s is at %s, not %s", a.branch, a.short(tip), want),
149 act{run: "valley approve " + shellQuote(a.branch)})
150 return 1
151 }
152 }
153 }
154 return a.run()
155}
156
157// verbFlags reads the approve verb's arguments, and returns --head's value.
158func (a *approval) verbFlags(args []string) (want string, err error) {
159 for i := 0; i < len(args); i++ {
160 switch arg := args[i]; {
161 case arg == "--build-here":
162 a.buildHere = true
163 case arg == "-v" || arg == "--verbose":
164 a.verbose = true
165 case arg == "--head" && i+1 < len(args):
166 want = args[i+1]
167 i++
168 case strings.HasPrefix(arg, "--head="):
169 want = strings.TrimPrefix(arg, "--head=")
170 case strings.HasPrefix(arg, "-") || a.name != "":
171 return "", failure(approveUsage)
172 default:
173 a.name = arg
174 }
175 }
176 if a.name == "" {
177 return "", failure(approveUsage)
178 }
179 return want, nil
180}
181
182// reviewApproval is review's [a]pprove of the change it shows, c, bound
183// to head and, for a change with a record, to version. name is the change
184// as review was given it, read again before filing. A plain branch's
185// attempt is told the branch, and the head review showed when it showed
186// one. carried is set when review's line that the answer carries ended the
187// line its prompt left open.
188func reviewApproval(g git, stdout, stderr io.Writer, c shownChange, head, version string, verbose, buildHere, carried bool) *approval {
189 a := &approval{g: g, stdout: stdout, stderr: stderr, reviewing: true, carried: carried,
190 verbose: verbose, buildHere: buildHere, name: c.name, bound: head}
191 if c.id == "" {
192 a.branch = c.branch
193 return a
194 }
195 // Review shows a change at its active version's head, and binds
196 // [a]pprove to it.
197 a.id, a.handle, a.version, a.head, a.boundVersion = c.id, c.handle, version, head, version
198 return a
199}
200
201// run is one attempt, its telemetry run, and its outcome: 0 when it
202// filed, 1 when it did not.
203func (a *approval) run() int {
204 // Off a terminal, the answer to review's prompt ends no line, so the
205 // verdict starts its own, unless the carry line has ended it.
206 if a.reviewing && !a.carried {
207 if _, tty := windowColumns(os.Stdin); !tty {
208 fmt.Fprintln(a.stdout)
209 }
210 }
211 t := a.beginTelemetry()
212 a.mu.Lock()
213 a.tel = t
214 a.mu.Unlock()
215 err := a.attempt()
216 if !a.finish() {
217 select {} // the signal handler ends the process
218 }
219 switch {
220 case err == nil:
221 a.tel.end("filed")
222 a.writeOutcome("approved", a.filedID, a.filedHandle, a.filedVersion, a.bound)
223 return 0
224 case a.failedAt != "":
225 a.tel.end("refused")
226 a.writeOutcome("checks-failed", a.failedAt)
227 case errors.Is(err, errUnknown):
228 a.tel.end("refused")
229 a.writeOutcome("unknown")
230 default:
231 a.tel.end("refused")
232 a.writeOutcome("refused")
233 }
234 return 1
235}
236
237// writeOutcome keeps how the attempt ended, for review.
238func (a *approval) writeOutcome(fields ...string) {
239 a.mu.Lock()
240 a.result = fields
241 a.mu.Unlock()
242}
243
244// watch takes over the signals given until unwatch: one interrupts the
245// attempt. The approve verb is interrupted by SIGINT and SIGTERM. Review's
246// [a]pprove is interrupted by SIGINT alone, which a terminal's Ctrl-C sends
247// to the checks as well, and review acts on a SIGTERM once the attempt has
248// ended (review.go).
249func (a *approval) watch(signals ...os.Signal) {
250 a.signals = make(chan os.Signal, 2)
251 signal.Notify(a.signals, signals...)
252 go func() {
253 <-a.signals
254 a.interrupt()
255 }()
256}
257
258// unwatch gives the signals back once the attempt has ended.
259func (a *approval) unwatch() { signal.Stop(a.signals) }
260
261// interrupt ends an attempt a signal cut short: it stops the checks
262// running, if any, waits for them to end, removes their worktree, records
263// the attempt's end as interrupted, keeps that result, and exits 130
264// through exitWith, which review sets to end its review first. A second signal while the checks are ending kills them. A
265// signal that reaches the checks first ends them, and checking's caller
266// interrupts the attempt itself; whichever comes first ends it.
267func (a *approval) interrupt() {
268 a.mu.Lock()
269 if a.finished {
270 a.mu.Unlock()
271 exitWith(interruptedStatus)
272 }
273 if a.interrupted {
274 a.mu.Unlock()
275 select {} // the first interrupt ends the process
276 }
277 a.interrupted = true
278 child, done, t := a.child, a.childDone, a.tel
279 a.mu.Unlock()
280 if child != nil {
281 _ = child.Signal(os.Interrupt)
282 select {
283 case <-done:
284 case <-a.signals:
285 _ = child.Kill()
286 <-done
287 }
288 }
289 a.removeWorktree()
290 t.end("interrupted")
291 a.writeOutcome("interrupted")
292 exitWith(interruptedStatus)
293}
294
295// finish marks the attempt ended, unless a signal has interrupted it,
296// when it reports false and the signal handler ends the process.
297func (a *approval) finish() bool {
298 a.mu.Lock()
299 defer a.mu.Unlock()
300 a.finished = !a.interrupted
301 return a.finished
302}
303
304func (a *approval) stopped() bool {
305 a.mu.Lock()
306 defer a.mu.Unlock()
307 return a.interrupted
308}
309
310// exitWith ends the process with status, recording the command first for
311// a verb bin/valley execs this program for. main sets it.
312var exitWith = os.Exit
313
314// act is what a refusal tells the person to do next: a command to run,
315// one to read, or what to do when it is no command.
316type act struct{ run, see, then string }
317
318// declined says what stops the approval, as a verdict on stderr, and
319// returns errRefused. A change is named by its handle and the version
320// being approved, a plain branch by its name.
321func (a *approval) declined(why string, next act) error {
322 return a.refused(verdict{why: why, run: next.run, see: next.see, then: next.then, required: -1, passed: -1})
323}
324
325func (a *approval) refused(v verdict) error {
326 if a.stopped() {
327 return errRefused
328 }
329 v.outcome, v.target, v.name = "refused", "main", a.label()
330 if a.id != "" {
331 v.version = a.boundVersion
332 if v.version == "" {
333 v.version = a.version
334 }
335 }
336 fmt.Fprint(a.stderr, v.lines(terminalOf(a.stderr)))
337 return errRefused
338}
339
340// label is the change as the verdict names it: its handle, or a plain
341// branch's name.
342func (a *approval) label() string {
343 if a.handle != "" {
344 return a.handle
345 }
346 return a.branch
347}
348
349// quoted is the change as a command offered names it.
350func (a *approval) quoted() string { return shellQuote(a.label()) }
351
352func (a *approval) short(oid string) string {
353 s, _ := a.g.output(true, "rev-parse", "--short", oid)
354 return s
355}
356
357// subject is one line of a commit, for saying which commit is meant. A
358// request being replaced is usually this operator's own pre-rebase head;
359// one another operator filed may not be in this repository.
360func (a *approval) subject(oid string) string {
361 if s, err := a.g.output(true, "log", "-1", "--format=%s", oid); err == nil && s != "" {
362 return s
363 }
364 return "subject not in this repository"
365}
366
367// notReady refuses a change that is not ready, offering its owner, as
368// git config valley.principal names them, the command that readies it
369// again. A review is the operator's and the change is usually someone
370// else's, so review is offered nothing.
371func (a *approval) notReady(state, id, branch, owner string) error {
372 why := "change is " + state
373 if state == "draft" {
374 why = "change is a draft"
375 }
376 return a.declined(why, a.readyHint(id, branch, owner))
377}
378
379func (a *approval) readyHint(id, branch, owner string) act {
380 if a.reviewing || owner == "" {
381 return act{}
382 }
383 if principal, _ := a.g.output(true, "config", "valley.principal"); principal != owner {
384 return act{}
385 }
386 run := "valley ready --change " + id
387 if branch != "" {
388 run += " " + shellQuote(branch)
389 }
390 return act{run: run}
391}
392
393// bindHead binds the head approve files for a change with a record. With
394// --head it is exactly that head, which must be one of the record's
395// version heads while the change is ready, the active one or not: a front
396// end that shows the change its own way passes the head it showed, so
397// what is approved is what was seen. Without --head the person is shown
398// the active version's head and title and asked to confirm them, which
399// needs a terminal.
400func (a *approval) bindHead(want string) error {
401 if a.state != "ready" {
402 return a.notReady(a.state, a.id, a.branch, a.owner)
403 }
404 if want != "" {
405 var sha string
406 var err error
407 if headArgument.MatchString(want) {
408 sha, err = a.g.output(true, "rev-parse", "--verify", "--quiet", want+"^{commit}")
409 }
410 if sha == "" || err != nil {
411 return a.declined("--head "+want+" names no commit here", act{see: "valley status " + a.handle})
412 }
413 if err := a.checkVersion(sha); err != nil {
414 return err
415 }
416 a.bound = sha
417 return nil
418 }
419 if err := a.checkVersion(a.head); err != nil {
420 return err
421 }
422 if _, tty := windowColumns(os.Stdin); !tty {
423 return a.declined("no terminal to confirm the head, "+a.title,
424 act{run: "valley approve --head " + a.head + " " + a.handle})
425 }
426 fmt.Fprintf(a.stdout, "approve change %s v%s at %s, %s? [y/N] ", a.handle, a.boundVersion, a.head, a.title)
427 switch readLine(os.Stdin) {
428 case "y", "Y", "yes":
429 a.bound = a.head
430 return nil
431 }
432 return a.declined("not confirmed", act{})
433}
434
435// readLine reads one line, a byte at a time so that nothing after it is
436// taken from whatever reads the input next.
437func readLine(r io.Reader) string {
438 var line []byte
439 b := make([]byte, 1)
440 for {
441 n, err := r.Read(b)
442 if n == 1 {
443 if b[0] == '\n' {
444 break
445 }
446 line = append(line, b[0])
447 }
448 if err != nil {
449 break
450 }
451 }
452 return strings.TrimSuffix(string(line), "\r")
453}
454
455// checkVersion reads the change's versions from origin again, and
456// refuses unless the change is ready and head is one of its versions'
457// heads, whichever version is active by then: a record that moves after
458// review cannot change what lands, since the request names the head
459// approved. It binds that version's number and title.
460func (a *approval) checkVersion(head string) error {
461 a.boundVersion, a.title = "", ""
462 r, err := versionsOf(a.g, a.id)
463 if err != nil {
464 fmt.Fprintf(a.stderr, "valley: %s\n", err)
465 return a.declined("could not read the change's versions", act{})
466 }
467 var known []string
468 for _, v := range r.Versions {
469 known = append(known, fmt.Sprintf("v%d at %s", v.N, headOf(v)))
470 if headOf(v) == head {
471 a.boundVersion, a.title = strconv.Itoa(v.N), v.Title
472 }
473 }
474 if r.State != "ready" {
475 return a.notReady(r.State, a.id, a.branch, a.owner)
476 }
477 if a.boundVersion == "" {
478 return a.declined(fmt.Sprintf("%s is none of its versions (%s)", a.short(head), strings.Join(known, ", ")),
479 act{see: "valley status " + a.handle})
480 }
481 return nil
482}
483
484// checkRecord reads the change's record again from origin, and refuses
485// unless the change is still ready with the bound head among its
486// versions. The record was read when review or approve began, and another
487// principal may unready, withdraw or ready a new version of the change
488// while a review is open or the checks run. These reads save a run that
489// would come to nothing: the integrator makes the same check on origin.
490//
491// A name that read as a plain branch can come to name a change
492// meanwhile, so the last read before filing, given the head about to be
493// filed as acting, reads the name again: when it names a change now, the
494// change must be ready, and its active head must be that head.
495func (a *approval) checkRecord(acting string) error {
496 if a.id == "" {
497 if acting == "" {
498 return nil
499 }
500 r, err := resolveRecorded(a.g, a.name)
501 if err != nil {
502 fmt.Fprintf(a.stderr, "valley: %s\n", err)
503 return a.declined("could not read origin's records again", act{})
504 }
505 if r.id == "" {
506 return nil
507 }
508 if r.state != "ready" {
509 return a.declined(fmt.Sprintf("now change %s v%d, which is %s", r.handle, r.version, r.state),
510 a.readyHint(r.id, r.branch, r.owner))
511 }
512 if r.head != acting {
513 return a.declined(fmt.Sprintf("now change %s v%d, at another head", r.handle, r.version),
514 act{run: "valley review " + r.handle})
515 }
516 return nil
517 }
518 r, err := resolveRecorded(a.g, a.id)
519 if err != nil {
520 fmt.Fprintf(a.stderr, "valley: %s\n", err)
521 return a.declined("could not read the change's record again", act{})
522 }
523 if r.id != a.id {
524 return a.declined("origin no longer holds the change's record", act{})
525 }
526 if r.state != "ready" {
527 return a.notReady(r.state, a.id, r.branch, r.owner)
528 }
529 return a.checkVersion(a.bound)
530}
531
532// branchAtShown refuses unless the plain branch on origin is still at the
533// head bound to this approval. The operator reviewed a branch, and a
534// branch that moved holds commits nobody has read. origin itself is read,
535// not the tracking ref: a push from another checkout moves the branch
536// without moving this clone's ref.
537func (a *approval) branchAtShown() error {
538 now, err := a.remoteRef("refs/heads/" + a.branch)
539 switch {
540 case err != nil:
541 return a.declined("could not read origin/"+a.branch+" again", act{})
542 case now == "":
543 return a.declined("origin/"+a.branch+" is gone", act{})
544 case now != a.bound:
545 return a.declined(fmt.Sprintf("origin/%s moved from %s, the head shown, to %s", a.branch, a.short(a.bound), a.short(now)),
546 act{run: "valley review " + shellQuote(a.branch)})
547 }
548 return nil
549}
550
551// lsRemote lists origin's refs matching the patterns. ls-remote matches a
552// pattern against the tail of a ref name, so a caller compares each ref
553// it lists whole. A listing that fails is an error, never an empty one.
554func (a *approval) lsRemote(patterns ...string) (map[string]string, error) {
555 out, err := a.g.output(true, append([]string{"ls-remote", "origin"}, patterns...)...)
556 if err != nil {
557 return nil, err
558 }
559 refs := map[string]string{}
560 for _, line := range strings.Split(out, "\n") {
561 if oid, ref, ok := strings.Cut(line, "\t"); ok {
562 refs[ref] = oid
563 }
564 }
565 return refs, nil
566}
567
568// remoteRef is the value of a ref on origin, or "" when origin has none.
569func (a *approval) remoteRef(ref string) (string, error) {
570 refs, err := a.lsRemote(ref)
571 return refs[ref], err
572}
573
574// pushLookalike is a ref origin holds whose name ends in one of these,
575// other than the ref itself, or "". git push matches a destination as
576// rev-parse matches a name: with the ref missing on origin, a push to it
577// writes refs/heads/<ref> instead, and with both there it is refused as
578// ambiguous. So nothing is pushed while origin holds such a ref.
579func (a *approval) pushLookalike(refs ...string) (string, error) {
580 var patterns []string
581 exact := map[string]bool{}
582 for _, ref := range refs {
583 patterns = append(patterns, ref, ref+"/HEAD")
584 exact[ref] = true
585 }
586 listed, err := a.lsRemote(patterns...)
587 if err != nil {
588 return "", err
589 }
590 var others []string
591 for ref := range listed {
592 if !exact[ref] {
593 others = append(others, ref)
594 }
595 }
596 sort.Strings(others)
597 if len(others) == 0 {
598 return "", nil
599 }
600 return others[0], nil
601}
602
603// reportEvidence says, with -v, where the checks this run signed are
604// stored, for every failure after they have run.
605func (a *approval) reportEvidence(refs []string) {
606 if len(refs) == 0 || !a.verbose || a.stopped() {
607 return
608 }
609 fmt.Fprintln(a.stderr, "valley: the evidence is stored locally at:")
610 for _, ref := range refs {
611 fmt.Fprintf(a.stderr, " %s\n", ref)
612 }
613}
614
615// attestationStandsElsewhere reports whether origin holds one of these
616// attestation refs at a value other than the one being pushed. approve
617// pushes a ref of its own notes alone, and origin takes an existing one
618// only with every note it holds kept, so that is the one refusal
619// approving again will never clear.
620func (a *approval) attestationStandsElsewhere(digest string, refs []string) bool {
621 remote, err := a.lsRemote(attestationRefs + digest + "/*")
622 if err != nil {
623 return false
624 }
625 for _, ref := range refs {
626 have := remote[ref]
627 if have == "" {
628 continue
629 }
630 if want, err := a.g.output(true, "rev-parse", ref); err == nil && have != want {
631 return true
632 }
633 }
634 return false
635}
636
637// diagnosePush says why a push carrying the request ref failed, as
638// precisely as the state allows. Every such push is leased, and a lease
639// refuses when the ref is not where the read before it saw it: the
640// request was consumed, or another approval filed or moved it. Reading
641// the ref again tells them apart. Anything else is origin's own refusal,
642// which git has already printed.
643func (a *approval) diagnosePush(ref, pending string) error {
644 now, err := a.remoteRef(ref)
645 switch {
646 case err != nil || now == pending:
647 return a.declined("origin refused the push", act{})
648 case now == "":
649 return a.declined("the pending request was consumed meanwhile", act{see: "valley status " + a.quoted()})
650 }
651 return a.declined(fmt.Sprintf("another approval filed %s (%s) meanwhile", a.short(now), a.subject(now)),
652 act{run: "valley approve " + a.quoted()})
653}
654
655// requestName is the change segment of a request ref for a plain branch.
656// The integrator refuses a segment holding a slash (integrator/refs.go),
657// so a slash is written as a dash. The mapping is lossy: topic/x and
658// topic-x are one request, and approve cannot tell a sibling's request
659// from its own, so it prints the subject of any request it replaces.
660func requestName(branch string) string { return strings.ReplaceAll(branch, "/", "-") }
661
662// attempt is one approval attempt, from main's tip to the verdict.
663func (a *approval) attempt() error {
664 g := a.g
665 root, err := g.output(true, "rev-parse", "--show-toplevel")
666 if err != nil {
667 return a.declined("not in a git repository", act{})
668 }
669 // main's tip as the fetch left it, read once by its exact name. The
670 // merge base, the fast-forward and both policy layers are read at
671 // that one commit.
672 tip, ok, err := g.ref("refs/remotes/origin/main")
673 switch {
674 case err != nil:
675 return a.declined("could not read origin/main", act{run: "git fetch origin"})
676 case !ok:
677 return a.declined("origin has no main to approve onto", act{})
678 }
679
680 // A change with a record is filed at exactly the bound head, under its
681 // own request name, c-<change ID>, and only while its record says it
682 // is ready and lists that head as a version's. Where its branch is
683 // does not matter: the request names the head. A plain branch is
684 // filed at the head review showed, or else at its tip on origin.
685 var head, request, what, named string
686 switch {
687 case a.id != "":
688 if a.bound == "" {
689 return a.declined("no head is bound to this approval", act{})
690 }
691 if err := a.checkRecord(""); err != nil {
692 return err
693 }
694 head, request, named = a.bound, "c-"+a.id, a.handle
695 what = a.handle + " v" + a.boundVersion
696 case a.bound != "":
697 head, request, what, named = a.bound, requestName(a.branch), a.branch, a.branch
698 default:
699 oid, ok, err := g.ref("refs/remotes/origin/" + a.branch)
700 if err != nil || !ok {
701 return a.declined("origin has no branch "+a.branch, act{})
702 }
703 head, request, what, named = oid, requestName(a.branch), a.branch, a.branch
704 }
705 if a.id == "" && changeRequest.MatchString(request) {
706 return a.declined("the branch's request name "+request+" is change "+strings.TrimPrefix(request, "c-")+"'s",
707 act{then: "rename the branch, or name the change by its ID"})
708 }
709 base, err := g.output(true, "merge-base", tip, head)
710 if err != nil || !isObjectID(base) {
711 return a.declined("shares no history with main", act{})
712 }
713 ref := "refs/the-valley/integration-requests/main/" + request
714 a.tel.context(a.id, a.boundVersion, head)
715 a.tel.emit("approve.start", map[string]any{"what": what, "request": ref})
716
717 // A head that does not fast-forward from main, and would bring a
718 // version of another change that has not landed, is a layer above the
719 // bottom of a stale stack. The integrator could land it all the same,
720 // as one commit recorded against this request alone, and the changes
721 // under it would have no landing record of their own. So the stack is
722 // rebased first. This is the project's choice, not a rule the
723 // integrator needs: a stale head with no change under it is approved
724 // as it is, and the integrator merges it onto main.
725 if !g.succeeds(true, "merge-base", "--is-ancestor", tip, head) {
726 under, err := bringsOf(g, a.id, head)
727 if err != nil {
728 fmt.Fprintf(a.stderr, "valley: %s\n", err)
729 return a.declined("could not read which changes it would bring to main", act{})
730 }
731 if len(under) > 0 {
732 return a.declined("stack is behind main (includes "+strings.Join(under, ", ")+")",
733 act{run: "valley rebase " + shellQuote(named)})
734 }
735 }
736
737 // What the policy requires of the change, read out of exactly the
738 // sources the integrator reads: both layers at the target's tip, and
739 // the floor from the owning valley's own tip when the tip names one. A
740 // change never supplies the policy that gates it, and neither does
741 // the checkout this runs from.
742 res, label, plabel, err := a.derive(root, tip, base, head)
743 if err != nil {
744 fmt.Fprintf(a.stderr, "valley: %s\n", err)
745 return a.declined("the policy did not derive", act{})
746 }
747 required := res.Required
748 names := make([]string, len(required))
749 for i, q := range required {
750 names[i] = q.Name
751 }
752 a.tel.emit("approve.policy", map[string]any{"required": names, "instance": label, "project": plabel})
753
754 // A change the policy asks nothing of is still a change, and the
755 // integrator lands a request that requires no check: nothing is
756 // signed, no key is needed, and one request ref is published.
757 //
758 // A required nix check whose evidence origin already holds is reused,
759 // not built again: a check worker, or an earlier approval, may have
760 // published it. A read of origin that fails ends the approval rather
761 // than reading as no evidence.
762 var reused, missing, unbuilt []string
763 var e evidence
764 if len(required) > 0 {
765 if _, err := exec.LookPath("attest"); err != nil {
766 return a.declined("the attest helper is not installed", act{then: "nix run .#valley bundles it"})
767 }
768 var asked []nixCheck
769 for _, q := range required {
770 if q.Runner == "nix" {
771 asked = append(asked, nixCheck{q.Name, q.Attribute})
772 }
773 }
774 // What coverage and the git it runs say is shown only with -v.
775 quiet := g
776 var said io.Writer = io.Discard
777 if a.verbose {
778 said = a.stderr
779 } else {
780 quiet.stderr = io.Discard
781 }
782 if e, err = coverageOf(quiet, head, asked, said); err != nil {
783 if a.verbose {
784 fmt.Fprintf(a.stderr, "valley: %s\n", err)
785 }
786 return a.declined("could not read the evidence origin holds", act{run: "valley approve -v " + a.quoted()})
787 }
788 // A check whose evidence on origin records a failure is judged by
789 // that evidence, so building it again changes nothing for this
790 // tree, and nothing is filed.
791 var failed []string
792 for _, c := range asked {
793 if _, ok := e.failed[c.name]; ok {
794 failed = append(failed, c.name)
795 }
796 }
797 if len(failed) > 0 {
798 a.failedAt = head
799 return a.refused(verdict{required: len(required), passed: -1, failed: failed})
800 }
801 var signedBy []string
802 for _, q := range required {
803 if by, ok := e.covered[q.Name]; ok {
804 reused = append(reused, q.Name)
805 signedBy = append(signedBy, q.Name+"="+signerOf(by))
806 } else {
807 missing = append(missing, q.Name)
808 }
809 }
810 a.tel.emit("approve.coverage", map[string]any{"tree": e.digest, "reused": list(reused),
811 "reused_by": list(signedBy), "missing": list(missing)})
812 if a.verbose && len(reused) > 0 {
813 fmt.Fprintf(a.stdout, "reusing the evidence origin holds for %s at %s, tree %s:\n", what, a.short(head), e.digest)
814 for _, check := range reused {
815 fmt.Fprintf(a.stdout, " %-24s signed by %s\n", check, signerOf(e.covered[check]))
816 }
817 }
818 }
819
820 // A required nix check with no evidence on origin is built here only
821 // with --build-here. The host's check worker builds the same checks
822 // for a ready change and publishes the evidence, so without the flag
823 // approve files the request at once without it, and the integrator
824 // holds the request until the evidence arrives. Whether the worker
825 // publishes at all is not assured. A command check is never reused and
826 // no worker runs one, so it runs here either way. From here on,
827 // missing is what runs here, and unbuilt what nothing here builds.
828 runner := map[string]derive.Required{}
829 for _, q := range required {
830 runner[q.Name] = q
831 }
832 if !a.buildHere {
833 var here []string
834 for _, check := range missing {
835 if runner[check].Runner == "nix" {
836 unbuilt = append(unbuilt, check)
837 } else {
838 here = append(here, check)
839 }
840 }
841 missing = here
842 }
843
844 var evidenceRefs []string
845 took := ""
846 if len(missing) > 0 {
847 if evidenceRefs, took, err = a.check(head, e, required, reused, missing, runner); err != nil {
848 return err
849 }
850 } else if len(required) == 0 && a.verbose {
851 fmt.Fprintf(a.stdout, "%s requires no check under %s + %s; filing the request with no evidence\n", what, label, plabel)
852 }
853
854 // What origin holds for this request, read once. Approving the same
855 // change twice is ordinary: evidence expires, and a change whose input
856 // closure moved under it is told to re-attest. So the request ref may
857 // already exist. A ref whose name ends in the request's, or in an
858 // evidence ref's, would take the push in its place.
859 pending, err := a.remoteRef(ref)
860 lookalike := ""
861 if err == nil {
862 lookalike, err = a.pushLookalike(append([]string{ref}, evidenceRefs...)...)
863 }
864 if err != nil {
865 a.declined("could not read the request ref on origin", act{})
866 a.reportEvidence(evidenceRefs)
867 return errRefused
868 }
869 if lookalike != "" {
870 a.declined("origin holds "+lookalike+", which git would push to in place of a ref approve pushes",
871 act{then: "delete " + lookalike + " on origin"})
872 a.reportEvidence(evidenceRefs)
873 return errRefused
874 }
875
876 // The one push: every evidence ref, and the request ref wherever it
877 // has to go, --atomic, so a hook that refuses any of them leaves
878 // origin as it was.
879 //
880 // Every write of the request ref is leased against what the read above
881 // saw, including nothing: --force-with-lease=<ref>: refuses if the ref
882 // exists at all, so filing for the first time is a compare-and-swap
883 // too, and two operators filing one change at once cannot have the
884 // second silently replace the first. The lease is the whole of the
885 // force and no refspec carries a +, which would defeat the lease.
886 //
887 // A request already at this head is a re-attestation: the ref does not
888 // move, so it is left out of the push, which carries no
889 // compare-and-swap on a ref it does not change. Where it stands
890 // afterwards is read again below. A request at another head is
891 // replaced: a rebased head is no descendant of the old one.
892 var push, lease []string
893 for _, spec := range evidenceRefs {
894 push = append(push, spec+":"+spec)
895 }
896 if pending != head {
897 lease = append(lease, "--force-with-lease="+ref+":"+pending)
898 push = append(push, head+":"+ref)
899 }
900
901 // The checks can take minutes, and the record may have moved
902 // meanwhile, so it is read once more just before anything is filed.
903 //
904 // A window remains between this read and the push. A change unreadied
905 // or withdrawn in it is filed all the same: git compares only the refs
906 // a push changes, and the record ref is not one of them, so no client
907 // can make the filing conditional on the record. The integrator
908 // narrows the window: it lands no request that would bring a version
909 // of a change that is not ready, and reads the records last just
910 // before it moves the target, so only a record written in that moment
911 // is missed.
912 if err := a.checkRecord(head); err != nil {
913 a.reportEvidence(evidenceRefs)
914 return err
915 }
916 if a.id == "" && a.bound != "" {
917 if err := a.branchAtShown(); err != nil {
918 a.reportEvidence(evidenceRefs)
919 return err
920 }
921 }
922
923 // With no new evidence and the request already at this head there is
924 // nothing to push, and a push with no refspec would fall back to
925 // origin's default one, so none is made.
926 pushed := false
927 if len(push) > 0 {
928 pushed = true
929 args := append(append([]string{"push", "--atomic", "--quiet"}, lease...), "origin")
930 cmd := exec.Command("git", append(args, push...)...)
931 cmd.Env, cmd.Stdout, cmd.Stderr = g.env, a.stderr, a.stderr
932 processStarted()
933 if err := cmd.Run(); err != nil {
934 a.tel.emit("approve.request", map[string]any{"ref": ref, "result": "refused"})
935 if len(lease) == 0 && a.attestationStandsElsewhere(e.digest, evidenceRefs) {
936 a.declined("this key's evidence for the tree is on origin already",
937 act{then: "attest with another key: set VALLEY_ATTEST_KEY"})
938 } else {
939 a.diagnosePush(ref, pending)
940 }
941 a.reportEvidence(evidenceRefs)
942 return errRefused
943 }
944 a.tel.emit("approve.request", map[string]any{"ref": ref, "result": "pushed"})
945 }
946
947 // The lines -v adds under the request line.
948 var standing []string
949 if pending == head {
950 // The request ref was not in that push, so where it stands now is
951 // read again: the integrator may have landed the change and
952 // consumed it, or another approval replaced it. Nothing here
953 // writes it back. Re-creating a consumed request would file a
954 // change already in the stream, replacing another approval's
955 // would clobber the winner, and either would be a second push. The
956 // approval stood before this run, so a request that cannot be read
957 // leaves its state unknown rather than unapproved; approving again
958 // takes the create or replace path against what is there.
959 after, err := a.remoteRef(ref)
960 if err != nil || after == "" {
961 v := verdict{outcome: "unknown", name: a.label(), required: -1, passed: -1}
962 if a.id != "" {
963 v.version = a.boundVersion
964 }
965 if err == nil {
966 v.why = "request consumed meanwhile"
967 }
968 if !a.stopped() {
969 fmt.Fprint(a.stdout, v.lines(terminalOf(a.stdout)))
970 }
971 a.reportEvidence(evidenceRefs)
972 return errUnknown
973 }
974 if after != head {
975 a.declined(fmt.Sprintf("another approval filed %s (%s) meanwhile", a.short(after), a.subject(after)),
976 act{run: "valley approve " + a.quoted()})
977 a.reportEvidence(evidenceRefs)
978 return errRefused
979 }
980 switch {
981 case pushed:
982 standing = append(standing, "the request already stood at this head; the evidence is what was published")
983 case len(unbuilt) > 0:
984 standing = append(standing, "the request already stood at this head, and nothing was built or published")
985 case len(required) > 0:
986 standing = append(standing, "the request already stood at this head and origin already held the evidence, so nothing needed publishing")
987 default:
988 standing = append(standing, "the request already stood at this head and nothing was required, so nothing needed publishing")
989 }
990 } else if pending != "" {
991 standing = append(standing, fmt.Sprintf("replaced the pending request, which stood at %s (%s)", a.short(pending), a.subject(pending)))
992 }
993
994 if a.verbose {
995 w := a.stdout
996 fmt.Fprintf(w, " request %s -> %s\n", ref, a.short(head))
997 for _, s := range standing {
998 fmt.Fprintf(w, " %s\n", s)
999 }
1000 if len(required) == 0 {
1001 fmt.Fprintln(w, " evidence none — nothing was required, so nothing was signed")
1002 fmt.Fprintln(w, " checks none — the policy requires no check of this change")
1003 } else {
1004 fmt.Fprintf(w, " tree %s\n", e.digest)
1005 for _, spec := range evidenceRefs {
1006 fmt.Fprintf(w, " evidence %s\n", spec)
1007 }
1008 // The refs on origin whose evidence was reused, each once.
1009 shown := map[string]bool{}
1010 for _, check := range reused {
1011 spec, _, _ := strings.Cut(e.covered[check], " ")
1012 if !shown[spec] {
1013 shown[spec] = true
1014 fmt.Fprintf(w, " reused %s\n", spec)
1015 }
1016 }
1017 if len(unbuilt) > 0 {
1018 fmt.Fprintf(w, " missing %s\n", strings.Join(unbuilt, ", "))
1019 }
1020 fmt.Fprintf(w, " checks %s\n", strings.Join(names, ", "))
1021 }
1022 }
1023
1024 // The verdict. Checks with no evidence yet are built by a check
1025 // worker only for a ready change's active version. Elsewhere approve
1026 // offers to build them here, unless a command check that ran here put
1027 // this signer's evidence for the tree on origin, which approve cannot
1028 // add to, so a plain branch is offered readying instead, which lets a
1029 // worker build it.
1030 v := verdict{outcome: "approved", name: a.label(), target: "main", required: len(required),
1031 passed: len(required) - len(unbuilt), took: took, waiting: unbuilt}
1032 if a.id != "" {
1033 v.version = a.boundVersion
1034 }
1035 if len(unbuilt) > 0 {
1036 switch {
1037 case a.id != "" && head == a.head:
1038 v.worker = true
1039 case len(missing) == 0:
1040 at := ""
1041 if a.id != "" {
1042 at = "--head " + a.short(head) + " "
1043 }
1044 v.run = "valley approve --build-here " + at + a.quoted()
1045 case a.id == "":
1046 v.run = "valley ready " + a.quoted()
1047 default:
1048 v.see = "valley status " + a.quoted()
1049 }
1050 }
1051 if !a.stopped() {
1052 fmt.Fprint(a.stdout, v.lines(terminalOf(a.stdout)))
1053 }
1054 a.filedID, a.filedHandle, a.filedVersion = a.id, a.handle, a.boundVersion
1055 if a.id == "" {
1056 a.filedVersion = ""
1057 }
1058 return nil
1059}
1060
1061// derive is what the policy at main's tip requires of the change from
1062// base to head, and where each layer was read from.
1063func (a *approval) derive(root, tip, base, head string) (res *derive.Result, label, plabel string, err error) {
1064 g := a.g
1065 schema, err := schemaFile(g, "")
1066 if err != nil {
1067 return nil, "", "", err
1068 }
1069 src, done, err := resolveLayers(g, tip, "", "")
1070 defer done()
1071 if err != nil {
1072 return nil, "", "", fmt.Errorf("%v; nothing derived", err)
1073 }
1074 model, err := policyModel(schema, src.instance, src.project, false)
1075 if err != nil {
1076 return nil, "", "", err
1077 }
1078 paths, err := derive.Diff(context.Background(), g.dir, g.env, base, head)
1079 if err != nil {
1080 return nil, "", "", fmt.Errorf("%v; nothing derived", err)
1081 }
1082 if res, err = derive.Derive(model, paths); err != nil {
1083 return nil, "", "", fmt.Errorf("%v; nothing derived", err)
1084 }
1085 label, plabel = src.labels(root, "", "", "origin/main "+a.short(tip))
1086 return res, label, plabel, nil
1087}
1088
1089// check runs the missing checks over head in a throwaway worktree, signed
1090// with this host's key, and returns every attestation ref stored here for
1091// the head's tree and how long the checks took.
1092func (a *approval) check(head string, e evidence, required []derive.Required, reused, missing []string, runner map[string]derive.Required) (refs []string, took string, err error) {
1093 key := os.Getenv("VALLEY_ATTEST_KEY")
1094 if key == "" {
1095 return nil, "", a.declined("no signing key", act{then: "set VALLEY_ATTEST_KEY to the ed25519 key this host attests with"})
1096 }
1097 if st, err := os.Stat(key); err != nil || !st.Mode().IsRegular() {
1098 return nil, "", a.declined("no signing key at "+key, act{})
1099 }
1100 signer := []string{"--key", key}
1101 if name := os.Getenv("VALLEY_ATTEST_NAME"); name != "" {
1102 signer = append(signer, "--name", name)
1103 }
1104
1105 // The ref this run's evidence goes to is keyed by the tree and this
1106 // signer's key hash, and approve pushes it holding this run's notes
1107 // alone, which origin refuses once it holds the ref. So origin
1108 // holding it is refused before anything is built.
1109 keyCmd := exec.Command("attest", append([]string{"key"}, signer...)...)
1110 keyCmd.Stderr = a.stderr
1111 processStarted()
1112 verifier, err := keyCmd.Output()
1113 if err != nil {
1114 return nil, "", a.declined("could not read the signing key at "+key, act{})
1115 }
1116 _, keyhash, _ := strings.Cut(strings.TrimRight(string(verifier), "\n"), "+")
1117 keyhash, _, _ = strings.Cut(keyhash, "+")
1118 if e.listed[attestationRefs+e.digest+"/"+keyhash] != "" {
1119 return nil, "", a.declined("this key's evidence for the tree, on origin, lacks "+strings.Join(missing, ", "),
1120 act{then: "attest with another key: set VALLEY_ATTEST_KEY"})
1121 }
1122
1123 // attest logs how long each check took, on this machine and outside
1124 // the evidence. What it cannot know itself is passed in: the change,
1125 // and each check's declared cost.
1126 timing := []string{"--timings"}
1127 if a.id != "" {
1128 timing = append(timing, "--change", a.id)
1129 }
1130 if a.boundVersion != "" {
1131 timing = append(timing, "--change-version", a.boundVersion)
1132 }
1133 var run []string
1134 for _, check := range missing {
1135 q := runner[check]
1136 switch q.Runner {
1137 case "nix":
1138 run = append(run, "--check", check+"="+q.Attribute)
1139 case "command":
1140 run = append(run, "--command", check+"="+q.Command)
1141 default:
1142 return nil, "", a.declined("the policy requires "+check+" but says no way to run it", act{})
1143 }
1144 if q.Cost != "" {
1145 timing = append(timing, "--cost", check+"="+q.Cost)
1146 }
1147 }
1148
1149 wt, err := os.MkdirTemp("", "valley-approve-")
1150 if err != nil {
1151 return nil, "", a.declined("no scratch directory to check it in", act{})
1152 }
1153 a.mu.Lock()
1154 a.worktree = wt
1155 a.mu.Unlock()
1156 defer a.removeWorktree()
1157 add := exec.Command("git", "worktree", "add", "--quiet", "--detach", wt, head)
1158 add.Env, add.Stdout, add.Stderr = a.g.env, a.stderr, a.stderr
1159 processStarted()
1160 if add.Run() != nil {
1161 a.removeWorktree()
1162 return nil, "", a.declined("could not check the head out to run its checks", act{})
1163 }
1164
1165 if a.tel != nil {
1166 timing = append(timing, "--telemetry", a.tel.spool, "--telemetry-run", a.tel.run+"-checks", "--project", a.tel.project)
1167 a.tel.emit("approve.checks", map[string]any{"attest_run": a.tel.run + "-checks", "checks": list(missing)})
1168 }
1169 v := verdict{name: a.label(), required: len(required), passed: len(reused)}
1170 if a.id != "" {
1171 v.version = a.boundVersion
1172 }
1173 args := append(append(append([]string{"run", "--repo", wt}, signer...), timing...), run...)
1174 cmd := exec.Command("attest", args...)
1175 cmd.Stdin = os.Stdin
1176 began := time.Now()
1177 done := make(chan struct{})
1178 a.mu.Lock()
1179 a.childDone = done
1180 a.mu.Unlock()
1181 status := v.checking(missing, cmd, a.verbose, droppable(a.stdout), droppable(a.stderr), a.started, a.stopped)
1182 a.mu.Lock()
1183 a.child = nil
1184 close(done)
1185 a.mu.Unlock()
1186 if a.stopped() || status == 128+int(syscall.SIGINT) || status == 128+int(syscall.SIGTERM) {
1187 a.interrupt()
1188 }
1189 if status != 0 {
1190 a.failedAt = head
1191 return nil, "", errRefused
1192 }
1193 took = fmt.Sprintf("%ds", int(time.Since(began).Seconds()))
1194 a.removeWorktree()
1195
1196 // Every attestation stored here for the tree, whoever signed it: the
1197 // evidence for this change is what the tree's digest keys, not what
1198 // this run happened to add.
1199 out, err := a.g.output(true, "for-each-ref", "--format=%(refname)", attestationRefs+e.digest)
1200 if err == nil && out != "" {
1201 refs = strings.Split(out, "\n")
1202 }
1203 if len(refs) == 0 {
1204 return nil, "", a.declined("no attestation is stored for the tree", act{})
1205 }
1206 return refs, took, nil
1207}
1208
1209// started is told of the attest run checking starts, so a signal can stop
1210// it.
1211func (a *approval) started(p *os.Process) {
1212 a.mu.Lock()
1213 a.child = p
1214 a.mu.Unlock()
1215}
1216
1217// removeWorktree removes the checks' worktree, if there is one.
1218func (a *approval) removeWorktree() {
1219 a.mu.Lock()
1220 wt := a.worktree
1221 a.worktree = ""
1222 a.mu.Unlock()
1223 if wt == "" {
1224 return
1225 }
1226 remove := exec.Command("git", "worktree", "remove", "--force", wt)
1227 remove.Env = a.g.env
1228 _ = remove.Run()
1229 _ = os.RemoveAll(wt)
1230}
1231
1232// signerOf is the signer of a covered check, as coverage maps it to
1233// "<ref> <signer>".
1234func signerOf(by string) string {
1235 _, signer, _ := strings.Cut(by, " ")
1236 return signer
1237}
1238
1239// list is a list as a telemetry record holds one: empty rather than null.
1240func list(items []string) []string {
1241 if items == nil {
1242 return []string{}
1243 }
1244 return items
1245}
1246
1247// approveTelemetry is an approval attempt's telemetry run, when the
1248// checkout has valley.telemetry on.
1249type approveTelemetry struct {
1250 emitter *telemetry.Emitter
1251 run, spool, project string
1252 began time.Time
1253 mu sync.Mutex
1254 about telemetry.Record
1255 ended bool
1256}
1257
1258// beginTelemetry starts the attempt's run, bound to the spool of the
1259// destination the checkout's telemetry remote names, and a flusher that
1260// sends it. Telemetry off is nil.
1261func (a *approval) beginTelemetry() *approveTelemetry {
1262 if on, _ := a.g.output(true, "config", "--get", "--bool", "valley.telemetry"); on != "true" {
1263 return nil
1264 }
1265 dest, err := telemetryRemote(a.g, "")
1266 if err == nil {
1267 var dir string
1268 if dir, err = bindSpool(dest); err == nil {
1269 version := producerStamp
1270 if version == "" {
1271 version = "unstamped"
1272 }
1273 t := &approveTelemetry{run: telemetry.NewRunID(), spool: dir, project: dest.project(), began: time.Now()}
1274 t.emitter = telemetry.NewEmitter(dir, telemetry.Self("valley", version), t.run)
1275 t.about.Project = t.project
1276 startFlusher()
1277 return t
1278 }
1279 }
1280 fmt.Fprintf(a.stderr, "valley: telemetry: %s\n", err)
1281 return nil
1282}
1283
1284// context is what every record of the attempt from here on is about.
1285func (t *approveTelemetry) context(id, version, head string) {
1286 if t == nil {
1287 return
1288 }
1289 n, _ := strconv.Atoi(version)
1290 t.mu.Lock()
1291 t.about.Change, t.about.Version, t.about.Head = id, n, head
1292 t.mu.Unlock()
1293}
1294
1295// emit records one step of the attempt. elapsed_ms is this machine's wall
1296// clock since the attempt began.
1297func (t *approveTelemetry) emit(typ string, data map[string]any) {
1298 if t == nil {
1299 return
1300 }
1301 t.mu.Lock()
1302 defer t.mu.Unlock()
1303 if t.ended {
1304 return
1305 }
1306 data["elapsed_ms"] = time.Since(t.began).Milliseconds()
1307 t.emitter.Emit(typ, t.about, data)
1308}
1309
1310// end records how the attempt ended: filed, refused or interrupted. Only
1311// the first end is recorded.
1312func (t *approveTelemetry) end(result string) {
1313 if t == nil {
1314 return
1315 }
1316 t.emit("approve.end", map[string]any{"result": result})
1317 t.mu.Lock()
1318 t.ended = true
1319 t.mu.Unlock()
1320}