gunk-dev/the-valley

command.go

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