gunk-dev/the-valley

command.go

source499d9e61dfeemain's published tip history
11.1 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// repository g names has valley.telemetry on in g's environment, and
109// starts a flusher to send it. The record is the project's g's
110// configuration names. Telemetry off costs no process and writes nothing.
111// Like every workstation record it is best effort: whatever goes wrong
112// costs this record, and never the command's output or exit status.
113func (inv *invocation) record(g git, status int, timed bool) {
114 if inv == nil || !telemetryMentioned(g) {
115 return
116 }
117 elapsed := time.Since(inv.since)
118 data := inv.data(status, elapsed, timed)
119 g.stderr = io.Discard
120 listed, err := g.output(true, "config", "--get-regexp", `^(valley\.telemetry(\.remote)?|remote\..*\.url)$`)
121 if err != nil {
122 return
123 }
124 settings := map[string]string{}
125 for _, line := range strings.Split(listed, "\n") {
126 key, value, given := strings.Cut(line, " ")
127 if !given {
128 value = "true" // a key with no value is a true boolean
129 }
130 // git prints the section and the name in lower case, and the
131 // subsection, such as a remote's name, as it is.
132 settings[key] = value
133 }
134 switch strings.ToLower(settings["valley.telemetry"]) {
135 case "true", "yes", "on", "1":
136 default:
137 return
138 }
139 dest, err := remoteDest(func(key string) (string, bool) {
140 v, ok := settings[key]
141 return strings.TrimSpace(v), ok
142 }, "")
143 if err != nil {
144 return
145 }
146 dir, err := bindSpool(dest)
147 if err != nil {
148 return
149 }
150 version := inv.version
151 if version == "" {
152 version = "unstamped"
153 }
154 // No executable: its path can name the user's home.
155 p := telemetry.Self("valley", version)
156 p.Exe = ""
157 telemetry.NewEmitter(dir, p, telemetry.NewRunID()).
158 Emit("command", telemetry.Record{Project: dest.project()}, data)
159 startFlusher()
160}
161
162// data is the record's data: the verb, its subverb for knot and
163// telemetry, the flag names given, the exit status, the wall time since
164// bin/valley started, and, when this process timed the command, each
165// phase's milliseconds and processes started. shell is bin/valley's time
166// before this process started, such as pending's fetch of origin.
167func (inv *invocation) data(status int, elapsed time.Duration, timed bool) map[string]any {
168 verb, sub, flags := commandWords(inv.args)
169 d := map[string]any{"verb": verb, "flags": flags, "status": int64(status), "elapsed_ms": elapsed.Milliseconds()}
170 if sub != "" {
171 d["subverb"] = sub
172 }
173 if !timed {
174 return d
175 }
176 c := phases
177 c.mu.Lock()
178 defer c.mu.Unlock()
179 c.switchTo(c.current)
180 d["shell_ms"] = max(c.began.Sub(inv.since).Milliseconds(), 0)
181 for name, t := range c.spent {
182 d[name+"_ms"] = t.Milliseconds()
183 d[name+"_procs"] = c.procs[name]
184 }
185 return d
186}
187
188// knownFlags is every flag a valley verb takes, from the usage texts and
189// bin/valley's own verbs. A word that looks like a flag and is not one
190// may be an argument's value, so it is left out.
191var knownFlags = func() map[string]bool {
192 flagRE := regexp.MustCompile(`(?:^|[\s\[|(])(--?[a-z][a-z0-9-]*)`)
193 shell := " --build-here --checks --change --head --verbose --cost --instance --names --project --schema -v -h --help"
194 known := map[string]bool{}
195 for _, m := range flagRE.FindAllStringSubmatch(usage+knotUsage+telemetryUsage+shell, -1) {
196 known[m[1]] = true
197 }
198 return known
199}()
200
201// The subverbs a record names: knot's verbs and telemetry's operations.
202var (
203 knotVerbs = func() map[string]bool {
204 known := map[string]bool{}
205 for _, m := range regexp.MustCompile(`(?m)^ ([a-z]+) `).FindAllStringSubmatch(knotUsage, -1) {
206 known[m[1]] = true
207 }
208 return known
209 }()
210 telemetryOps = map[string]bool{"sources": true, "snapshot": true, "read": true, "follow": true,
211 "flush": true, "start": true, "emit": true, "command": true}
212)
213
214// commandWords is an invocation's verb, its subverb, and the names of the
215// known flags it was given, each once, in the order given. Nothing after
216// -- is read, since everything there is a value.
217func commandWords(args []string) (verb, sub string, flags []string) {
218 verb, flags = args[0], []string{}
219 if verb == "walk" { // what valley review runs with no change (walk.go)
220 verb = "review"
221 }
222 if !knownVerbs[verb] {
223 verb = "unknown"
224 }
225 for _, arg := range args[1:] {
226 if arg == "--" {
227 break
228 }
229 name, _, _ := strings.Cut(arg, "=")
230 switch {
231 case knownFlags[name] && strings.HasPrefix(name, "-"):
232 if !slices.Contains(flags, name) {
233 flags = append(flags, name)
234 }
235 case sub == "" && verb == "knot" && knotVerbs[arg], sub == "" && verb == "telemetry" && telemetryOps[arg]:
236 sub = arg
237 }
238 }
239 return verb, sub, flags
240}
241
242// knownVerbs is valley's verbs (bin/valley's main).
243var knownVerbs = map[string]bool{"pending": true, "changes": true, "review": true, "approve": true,
244 "rebase": true, "status": true, "ready": true, "unready": true, "withdraw": true, "knot": true,
245 "plan": true, "checks": true, "tail": true, "replay": true, "self-update": true, "telemetry": true}
246
247// telemetryMentioned reports whether a configuration file git reads in
248// g's repository and environment may set valley.telemetry, without
249// starting git: it is false only when none of them mentions telemetry or
250// includes another file. So a checkout with telemetry off starts no
251// process to find that out, and git itself answers whenever the files
252// could say yes.
253func telemetryMentioned(g git) bool {
254 for _, v := range []string{"GIT_DIR", "GIT_COMMON_DIR", "GIT_CONFIG", "GIT_CONFIG_GLOBAL",
255 "GIT_CONFIG_SYSTEM", "GIT_CONFIG_COUNT", "GIT_CONFIG_PARAMETERS"} {
256 if envValue(g.env, v) != "" {
257 return true
258 }
259 }
260 home := envValue(g.env, "HOME")
261 xdg := envValue(g.env, "XDG_CONFIG_HOME")
262 if xdg == "" {
263 xdg = filepath.Join(home, ".config")
264 }
265 files := []string{"/etc/gitconfig", filepath.Join(home, ".gitconfig"), filepath.Join(xdg, "git", "config")}
266 dirs, found := gitDirs(g.dir)
267 if !found {
268 return true
269 }
270 for _, dir := range dirs {
271 files = append(files, filepath.Join(dir, "config"), filepath.Join(dir, "config.worktree"))
272 }
273 for _, f := range files {
274 data, err := os.ReadFile(f)
275 if err != nil {
276 continue
277 }
278 data = bytes.ToLower(data)
279 if bytes.Contains(data, []byte("telemetry")) || bytes.Contains(data, []byte("include")) {
280 return true
281 }
282 }
283 return false
284}
285
286// envValue is the value env gives name, the last one given winning as it
287// does for a process started with env, or "".
288func envValue(env []string, name string) string {
289 value := ""
290 for _, kv := range env {
291 if k, v, ok := strings.Cut(kv, "="); ok && k == name {
292 value = v
293 }
294 }
295 return value
296}
297
298// gitDirs is the repository's git directory at or above from, the working
299// directory when from is "", and, for a linked worktree, its common
300// directory.
301func gitDirs(from string) ([]string, bool) {
302 dir, err := filepath.Abs(from)
303 if err != nil {
304 return nil, false
305 }
306 for {
307 dotgit := filepath.Join(dir, ".git")
308 if st, err := os.Stat(dotgit); err == nil {
309 if st.IsDir() {
310 return []string{dotgit}, true
311 }
312 data, err := os.ReadFile(dotgit)
313 linked, ok := strings.CutPrefix(strings.TrimSpace(string(data)), "gitdir: ")
314 if err != nil || !ok {
315 return nil, false
316 }
317 if !filepath.IsAbs(linked) {
318 linked = filepath.Join(dir, linked)
319 }
320 dirs := []string{linked}
321 if common, err := os.ReadFile(filepath.Join(linked, "commondir")); err == nil {
322 c := strings.TrimSpace(string(common))
323 if !filepath.IsAbs(c) {
324 c = filepath.Join(linked, c)
325 }
326 dirs = append(dirs, c)
327 }
328 return dirs, true
329 }
330 parent := filepath.Dir(dir)
331 if parent == dir {
332 return nil, false
333 }
334 dir = parent
335 }
336}
337
338// startFlusher sends the spools in the background, in a session of its
339// own, so the command neither waits for the host nor takes it down on
340// exit. One process starts one flusher.
341func startFlusher() {
342 flusherOnce.Do(flushInBackground)
343}
344
345var flusherOnce sync.Once
346
347func flushInBackground() {
348 exe, err := os.Executable()
349 if err != nil {
350 return
351 }
352 cmd := exec.Command(exe, "telemetry", "flush", "--watch", strconv.Itoa(os.Getpid()))
353 cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
354 if cmd.Start() == nil {
355 _ = cmd.Process.Release()
356 }
357}