gunk-dev/the-valley

command.go

source01f84ae34d8amain's published tip history
10.6 KiB
1package main
2
3import (
4 "bytes"
5 "io"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "regexp"
10 "slices"
11 "strconv"
12 "strings"
13 "sync"
14 "syscall"
15 "time"
16
17 "the-valley/telemetry"
18)
19
20// A valley invocation's command record (valley help telemetry): its verb,
21// the names of the flags it was given, its exit status, its wall time,
22// and the time and processes each phase of it took. It carries no
23// argument's value, since a report goes to the host and a project may be
24// public. bin/valley execs this program for most verbs, so this program
25// records them itself, once it has run; the verbs bin/valley runs itself
26// it records with `valley-go telemetry command` as it exits.
27
28// phaseClock is where this process's wall time goes: to the phase current
29// when it passes, and to "other" outside every phase. A phase's time
30// leaves out the phases entered from it. Work on another goroutine counts
31// toward whichever phase is current, so the times are a reading guide,
32// not a profile.
33type phaseClock struct {
34 mu sync.Mutex
35 began time.Time
36 current string
37 since time.Time
38 spent map[string]time.Duration
39 procs map[string]int64
40}
41
42var phases = &phaseClock{began: time.Now(), current: "other", since: time.Now(),
43 spent: map[string]time.Duration{}, procs: map[string]int64{}}
44
45// phase enters the phase name, and returns what leaves it for the phase
46// it was entered from.
47func phase(name string) (end func()) {
48 c := phases
49 c.mu.Lock()
50 defer c.mu.Unlock()
51 from := c.switchTo(name)
52 return func() {
53 c.mu.Lock()
54 defer c.mu.Unlock()
55 c.switchTo(from)
56 }
57}
58
59func (c *phaseClock) switchTo(name string) (from string) {
60 now := time.Now()
61 c.spent[c.current] += now.Sub(c.since)
62 from, c.current, c.since = c.current, name, now
63 return from
64}
65
66// processStarted counts a process toward the current phase.
67func processStarted() {
68 phases.mu.Lock()
69 phases.procs[phases.current]++
70 phases.mu.Unlock()
71}
72
73// invocation is the valley command a process records: the arguments it
74// was run with, when bin/valley started it, and bin/valley's version.
75type invocation struct {
76 args []string
77 since time.Time
78 version string
79}
80
81// execed is the invocation bin/valley execs this process as, or nil. The
82// variables are removed, so no program this one runs takes them for its
83// own.
84func execed(args []string) *invocation {
85 since, version := os.Getenv("VALLEY_TELEMETRY_SINCE"), os.Getenv("VALLEY_TELEMETRY_VERSION")
86 producerStamp = version
87 os.Unsetenv("VALLEY_TELEMETRY_SINCE")
88 os.Unsetenv("VALLEY_TELEMETRY_VERSION")
89 return invocationOf(args, since, version)
90}
91
92// stamp is bin/valley's version, which bin/valley passes as
93// VALLEY_TELEMETRY_VERSION, or "" for a script run from a checkout. It
94// names the producer of an approval's records (approve.go).
95var producerStamp string
96
97// invocationOf is an invocation started at since, in microseconds of the
98// Unix epoch as bash's EPOCHREALTIME reads with its point removed.
99func invocationOf(args []string, since, version string) *invocation {
100 us, err := strconv.ParseInt(since, 10, 64)
101 if err != nil || us <= 0 || len(args) == 0 {
102 return nil
103 }
104 return &invocation{args: args, since: time.UnixMicro(us), version: version}
105}
106
107// record stores the invocation's command record in the spool, when the
108// checkout has valley.telemetry on, and starts a flusher to send it.
109// Telemetry off costs no process and writes nothing. Like every
110// workstation record it is best effort: whatever goes wrong costs this
111// record, and never the command's output or exit status.
112func (inv *invocation) record(status int, timed bool) {
113 if inv == nil || !telemetryMentioned() {
114 return
115 }
116 elapsed := time.Since(inv.since)
117 data := inv.data(status, elapsed, timed)
118 g := git{env: gitEnvironment(os.Environ()), stderr: io.Discard}
119 listed, err := g.output(true, "config", "--get-regexp", `^(valley\.telemetry(\.remote)?|remote\..*\.url)$`)
120 if err != nil {
121 return
122 }
123 settings := map[string]string{}
124 for _, line := range strings.Split(listed, "\n") {
125 key, value, given := strings.Cut(line, " ")
126 if !given {
127 value = "true" // a key with no value is a true boolean
128 }
129 // git prints the section and the name in lower case, and the
130 // subsection, such as a remote's name, as it is.
131 settings[key] = value
132 }
133 switch strings.ToLower(settings["valley.telemetry"]) {
134 case "true", "yes", "on", "1":
135 default:
136 return
137 }
138 dest, err := remoteDest(func(key string) (string, bool) {
139 v, ok := settings[key]
140 return strings.TrimSpace(v), ok
141 }, "")
142 if err != nil {
143 return
144 }
145 dir, err := bindSpool(dest)
146 if err != nil {
147 return
148 }
149 version := inv.version
150 if version == "" {
151 version = "unstamped"
152 }
153 // No executable: its path can name the user's home.
154 p := telemetry.Self("valley", version)
155 p.Exe = ""
156 telemetry.NewEmitter(dir, p, telemetry.NewRunID()).
157 Emit("command", telemetry.Record{Project: dest.project()}, data)
158 startFlusher()
159}
160
161// data is the record's data: the verb, its subverb for knot and
162// telemetry, the flag names given, the exit status, the wall time since
163// bin/valley started, and, when this process timed the command, each
164// phase's milliseconds and processes started. shell is bin/valley's time
165// before this process started, such as pending's fetch of origin.
166func (inv *invocation) data(status int, elapsed time.Duration, timed bool) map[string]any {
167 verb, sub, flags := commandWords(inv.args)
168 d := map[string]any{"verb": verb, "flags": flags, "status": int64(status), "elapsed_ms": elapsed.Milliseconds()}
169 if sub != "" {
170 d["subverb"] = sub
171 }
172 if !timed {
173 return d
174 }
175 c := phases
176 c.mu.Lock()
177 defer c.mu.Unlock()
178 c.switchTo(c.current)
179 d["shell_ms"] = max(c.began.Sub(inv.since).Milliseconds(), 0)
180 for name, t := range c.spent {
181 d[name+"_ms"] = t.Milliseconds()
182 d[name+"_procs"] = c.procs[name]
183 }
184 return d
185}
186
187// knownFlags is every flag a valley verb takes, from the usage texts and
188// bin/valley's own verbs. A word that looks like a flag and is not one
189// may be an argument's value, so it is left out.
190var knownFlags = func() map[string]bool {
191 flagRE := regexp.MustCompile(`(?:^|[\s\[|(])(--?[a-z][a-z0-9-]*)`)
192 shell := " --build-here --checks --change --head --verbose --cost --instance --names --project --schema -v -h --help"
193 known := map[string]bool{}
194 for _, m := range flagRE.FindAllStringSubmatch(usage+knotUsage+telemetryUsage+shell, -1) {
195 known[m[1]] = true
196 }
197 return known
198}()
199
200// The subverbs a record names: knot's verbs and telemetry's operations.
201var (
202 knotVerbs = func() map[string]bool {
203 known := map[string]bool{}
204 for _, m := range regexp.MustCompile(`(?m)^ ([a-z]+) `).FindAllStringSubmatch(knotUsage, -1) {
205 known[m[1]] = true
206 }
207 return known
208 }()
209 telemetryOps = map[string]bool{"sources": true, "snapshot": true, "read": true, "follow": true,
210 "flush": true, "start": true, "emit": true, "command": true}
211)
212
213// commandWords is an invocation's verb, its subverb, and the names of the
214// known flags it was given, each once, in the order given. Nothing after
215// -- is read, since everything there is a value.
216func commandWords(args []string) (verb, sub string, flags []string) {
217 verb, flags = args[0], []string{}
218 if verb == "walk" { // what valley review runs with no change (walk.go)
219 verb = "review"
220 }
221 if !knownVerbs[verb] {
222 verb = "unknown"
223 }
224 for _, arg := range args[1:] {
225 if arg == "--" {
226 break
227 }
228 name, _, _ := strings.Cut(arg, "=")
229 switch {
230 case knownFlags[name] && strings.HasPrefix(name, "-"):
231 if !slices.Contains(flags, name) {
232 flags = append(flags, name)
233 }
234 case sub == "" && verb == "knot" && knotVerbs[arg], sub == "" && verb == "telemetry" && telemetryOps[arg]:
235 sub = arg
236 }
237 }
238 return verb, sub, flags
239}
240
241// knownVerbs is valley's verbs (bin/valley's main).
242var knownVerbs = map[string]bool{"pending": true, "changes": true, "review": true, "approve": true,
243 "rebase": true, "status": true, "ready": true, "unready": true, "withdraw": true, "knot": true,
244 "plan": true, "checks": true, "tail": true, "replay": true, "self-update": true, "telemetry": true}
245
246// telemetryMentioned reports whether a configuration file git reads here
247// may set valley.telemetry, without starting git: it is false only when
248// none of them mentions telemetry or includes another file. So a
249// checkout with telemetry off starts no process to find that out, and git
250// itself answers whenever the files could say yes.
251func telemetryMentioned() bool {
252 for _, v := range []string{"GIT_DIR", "GIT_COMMON_DIR", "GIT_CONFIG", "GIT_CONFIG_GLOBAL",
253 "GIT_CONFIG_SYSTEM", "GIT_CONFIG_COUNT", "GIT_CONFIG_PARAMETERS"} {
254 if os.Getenv(v) != "" {
255 return true
256 }
257 }
258 home := os.Getenv("HOME")
259 xdg := os.Getenv("XDG_CONFIG_HOME")
260 if xdg == "" {
261 xdg = filepath.Join(home, ".config")
262 }
263 files := []string{"/etc/gitconfig", filepath.Join(home, ".gitconfig"), filepath.Join(xdg, "git", "config")}
264 dirs, found := gitDirs()
265 if !found {
266 return true
267 }
268 for _, dir := range dirs {
269 files = append(files, filepath.Join(dir, "config"), filepath.Join(dir, "config.worktree"))
270 }
271 for _, f := range files {
272 data, err := os.ReadFile(f)
273 if err != nil {
274 continue
275 }
276 data = bytes.ToLower(data)
277 if bytes.Contains(data, []byte("telemetry")) || bytes.Contains(data, []byte("include")) {
278 return true
279 }
280 }
281 return false
282}
283
284// gitDirs is the repository's git directory above the working directory
285// and, for a linked worktree, its common directory.
286func gitDirs() ([]string, bool) {
287 dir, err := os.Getwd()
288 if err != nil {
289 return nil, false
290 }
291 for {
292 dotgit := filepath.Join(dir, ".git")
293 if st, err := os.Stat(dotgit); err == nil {
294 if st.IsDir() {
295 return []string{dotgit}, true
296 }
297 data, err := os.ReadFile(dotgit)
298 linked, ok := strings.CutPrefix(strings.TrimSpace(string(data)), "gitdir: ")
299 if err != nil || !ok {
300 return nil, false
301 }
302 if !filepath.IsAbs(linked) {
303 linked = filepath.Join(dir, linked)
304 }
305 dirs := []string{linked}
306 if common, err := os.ReadFile(filepath.Join(linked, "commondir")); err == nil {
307 c := strings.TrimSpace(string(common))
308 if !filepath.IsAbs(c) {
309 c = filepath.Join(linked, c)
310 }
311 dirs = append(dirs, c)
312 }
313 return dirs, true
314 }
315 parent := filepath.Dir(dir)
316 if parent == dir {
317 return nil, false
318 }
319 dir = parent
320 }
321}
322
323// startFlusher sends the spools in the background, in a session of its
324// own, so the command neither waits for the host nor takes it down on
325// exit. One process starts one flusher.
326func startFlusher() {
327 flusherOnce.Do(flushInBackground)
328}
329
330var flusherOnce sync.Once
331
332func flushInBackground() {
333 exe, err := os.Executable()
334 if err != nil {
335 return
336 }
337 cmd := exec.Command(exe, "telemetry", "flush", "--watch", strconv.Itoa(os.Getpid()))
338 cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
339 if cmd.Start() == nil {
340 _ = cmd.Process.Release()
341 }
342}