gunk-dev/the-valley

telemetry_test.go

source64f5539ce840main's published tip history
11.6 KiB
1package main
2
3import (
4 "bufio"
5 "bytes"
6 "encoding/json"
7 "fmt"
8 "io"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "regexp"
13 "strconv"
14 "strings"
15 "sync"
16 "testing"
17 "time"
18
19 "the-valley/telemetry"
20)
21
22// TestMain runs the test binary as the fake ssh the telemetry tests put
23// on PATH, when it is invoked under that name, as the checks read a
24// review starts, which runs this program's checkline (walk_test.go), and
25// as a signed approval's PIV device and racing receive-pack
26// (approvalsign_test.go).
27func TestMain(m *testing.M) {
28 if filepath.Base(os.Args[0]) == "ssh" {
29 if dir := os.Getenv("FAKE_SSH_UPLOAD"); dir != "" {
30 os.Exit(fakeUpload(dir, os.Args[1:]))
31 }
32 if dir := os.Getenv("FAKE_SSH_POOL"); dir != "" {
33 os.Exit(fakePooledSSH(dir, os.Args[1:]))
34 }
35 os.Exit(fakeSSH(os.Args[1:]))
36 }
37 if filepath.Base(os.Args[0]) == "attest" {
38 os.Exit(fakeAttest())
39 }
40 // A signed approval's stand-ins (approvalsign_test.go).
41 if scenario := os.Getenv("VALLEY_TEST_FAKE_PIV"); scenario != "" {
42 os.Exit(fakePIV(scenario))
43 }
44 if filepath.Base(os.Args[0]) == "racing-receive-pack" {
45 os.Exit(racingReceivePack(os.Args[1:]))
46 }
47 if len(os.Args) > 1 && os.Args[1] == checkBuildChild {
48 os.Exit(cli(os.Args[1:], os.Stdout, os.Stderr, os.Exit))
49 }
50 if os.Getenv("VALLEY_TEST_AS_MAIN") != "" {
51 // Run valley's own main, once the test has closed the reader of
52 // the output (pipe_test.go).
53 io.ReadFull(os.Stdin, make([]byte, 1))
54 os.Unsetenv("VALLEY_TEST_AS_MAIN")
55 main()
56 }
57 if len(os.Args) > 1 && os.Args[1] == "checkline" {
58 os.Exit(fakeCheckline())
59 }
60 os.Exit(m.Run())
61}
62
63// fakeSSH is a telemetry receiver per destination: it keeps every report
64// line it is sent in $FAKE_SSH_DIR/<destination>.jsonl and acknowledges
65// the newest record of each sender epoch, as the collector does, and
66// answers any other request with <destination>.answer there. A
67// destination with a .down file beside it cannot be reached.
68func fakeSSH(args []string) int {
69 dest, command, ok := sshDestCommand(args)
70 if !ok {
71 return 255
72 }
73 dir := os.Getenv("FAKE_SSH_DIR")
74 if _, err := os.Stat(filepath.Join(dir, dest+".down")); err == nil {
75 fmt.Fprintf(os.Stderr, "ssh: connect to host %s: Connection refused\n", dest)
76 return 255
77 }
78 if command != "valley-telemetry report" {
79 // A read or follow answers with $FAKE_SSH_DIR/<destination>.answer.
80 answer, err := os.ReadFile(filepath.Join(dir, dest+".answer"))
81 if err != nil {
82 return 1
83 }
84 os.Stdout.Write(answer)
85 return 0
86 }
87 body, _ := io.ReadAll(os.Stdin)
88 f, err := os.OpenFile(filepath.Join(dir, dest+".jsonl"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
89 if err != nil {
90 return 1
91 }
92 f.Write(body)
93 f.Close()
94 acked := map[string]int64{}
95 for _, line := range strings.Split(strings.TrimSpace(string(body)), "\n") {
96 var r telemetry.Record
97 if json.Unmarshal([]byte(line), &r) != nil {
98 continue
99 }
100 epoch, seq, _ := strings.Cut(r.ClientID, ":")
101 n, _ := strconv.ParseInt(seq, 10, 64)
102 acked[epoch] = max(acked[epoch], n)
103 }
104 ack, _ := json.Marshal(map[string]any{"kind": "ack", "acked": acked})
105 fmt.Printf("%s\n{\"kind\":\"end\"}\n", ack)
106 return 0
107}
108
109// sshDestCommand is the destination and command of ssh's arguments.
110func sshDestCommand(args []string) (dest, command string, ok bool) {
111 var rest []string
112 for i := 0; i < len(args); i++ {
113 switch args[i] {
114 case "-o", "-p":
115 i++
116 case "--":
117 rest = args[i+1:]
118 i = len(args)
119 }
120 }
121 if len(rest) != 2 {
122 fmt.Fprintln(os.Stderr, "fake ssh: no destination and command")
123 return "", "", false
124 }
125 return rest[0], rest[1], true
126}
127
128// received is what a fake receiver holds: each record by its client ID.
129func received(t *testing.T, dir, dest string) []telemetry.Record {
130 t.Helper()
131 f, err := os.Open(filepath.Join(dir, dest+".jsonl"))
132 if os.IsNotExist(err) {
133 return nil
134 }
135 if err != nil {
136 t.Fatal(err)
137 }
138 defer f.Close()
139 var recs []telemetry.Record
140 sc := bufio.NewScanner(f)
141 sc.Buffer(make([]byte, 64<<10), 1<<20)
142 for sc.Scan() {
143 r, err := telemetry.DecodeRecord(sc.Bytes())
144 if err != nil {
145 t.Fatalf("%s received %q: %v", dest, sc.Text(), err)
146 }
147 recs = append(recs, r)
148 }
149 return recs
150}
151
152// Each approval run's records go to the valley its checkout named when
153// the run began, and to no other: whichever checkout or remote a flush
154// runs from, whatever the checkout's remote says later, whichever
155// receiver is down, and however many flushes run at once.
156func TestSpoolsAreBoundToTheirDestinations(t *testing.T) {
157 if _, err := exec.LookPath("git"); err != nil {
158 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
159 t.Fatal("no git on PATH, and VALLEY_TEST_TOOLS=required")
160 }
161 t.Skip("no git on PATH")
162 }
163 t.Setenv("XDG_STATE_HOME", t.TempDir())
164 recv := t.TempDir()
165 t.Setenv("FAKE_SSH_DIR", recv)
166 bin := t.TempDir()
167 self, err := filepath.Abs(os.Args[0])
168 if err != nil {
169 t.Fatal(err)
170 }
171 if err := os.Symlink(self, filepath.Join(bin, "ssh")); err != nil {
172 t.Fatal(err)
173 }
174 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
175
176 checkout := func(origin string) git {
177 dir := t.TempDir()
178 for _, args := range [][]string{{"init", "--quiet"}, {"remote", "add", "origin", origin}} {
179 if out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput(); err != nil {
180 t.Fatalf("git %v: %v %s", args, err, out)
181 }
182 }
183 return git{env: gitEnvironment(os.Environ()), stderr: io.Discard, dir: dir}
184 }
185 tele := func(g git, args ...string) (string, error) {
186 var out, errs bytes.Buffer
187 err := runTelemetry(g, args, &out, &errs)
188 return out.String() + errs.String(), err
189 }
190 start := func(g git) (run, spool, project string) {
191 t.Helper()
192 out, err := tele(g, "start")
193 if err != nil {
194 t.Fatalf("start: %v %s", err, out)
195 }
196 f := strings.Split(strings.TrimSpace(out), "\t")
197 if len(f) != 3 {
198 t.Fatalf("start printed %q", out)
199 }
200 return f[0], f[1], f[2]
201 }
202 emit := func(g git, spool, run, typ string) {
203 t.Helper()
204 if out, err := tele(g, "emit", "--spool", spool, "--run", run, "--type", typ); err != nil {
205 t.Fatalf("emit: %v %s", err, out)
206 }
207 }
208 output := func(spool, run, text string) {
209 l := (&telemetry.Stream{Dir: spool}).Log(run+"-checks", "slow", 1<<20)
210 l.Write([]byte(text + "\n"))
211 l.Close()
212 }
213
214 a := checkout("ssh://git@valley-a/app.git")
215 b := checkout("git@valley-b:site.git")
216 runA, spoolA, projectA := start(a)
217 runB, spoolB, projectB := start(b)
218 if spoolA == spoolB || projectA != "app" || projectB != "site" {
219 t.Fatalf("spools %s %s, projects %s %s", spoolA, spoolB, projectA, projectB)
220 }
221 // Interleaved, as two approvals running at once write them.
222 emit(a, spoolA, runA, "approve.start")
223 emit(b, spoolB, runB, "approve.start")
224 output(spoolA, runA, "output of app")
225 emit(a, spoolA, runA, "approve.checks")
226 output(spoolB, runB, "output of site")
227 emit(b, spoolB, runB, "approve.checks")
228
229 // valley-b is down. A flush from b's checkout still sends a's run to
230 // valley-a alone, and says what it could not send.
231 os.WriteFile(filepath.Join(recv, "git@valley-b.down"), nil, 0o600)
232 if out, err := tele(b, "flush"); err == nil || !strings.Contains(out, "records sent to ssh://git@valley-a") {
233 t.Fatalf("flush with valley-b down: %v %s", err, out)
234 }
235 if got := received(t, recv, "git@valley-b"); got != nil {
236 t.Fatalf("valley-b, down, received %v", got)
237 }
238
239 // a's checkout moves to valley-b. Its open run still belongs to
240 // valley-a; only a run begun after the move goes to valley-b.
241 if out, err := exec.Command("git", "-C", a.dir, "remote", "set-url", "origin", "git@valley-b:app.git").CombinedOutput(); err != nil {
242 t.Fatalf("%v %s", err, out)
243 }
244 emit(a, spoolA, runA, "approve.end")
245 runA2, spoolA2, projectA2 := start(a)
246 if spoolA2 != spoolB || projectA2 != "app" {
247 t.Fatalf("a run begun after the move is in %s for %s, not valley-b's %s", spoolA2, projectA2, spoolB)
248 }
249 emit(a, spoolA2, runA2, "approve.start")
250 // --remote limits a flush to that destination's spool: it neither
251 // reroutes another's nor sends it.
252 if out, err := tele(b, "--remote", "ssh://git@valley-a", "flush"); err != nil || strings.Contains(out, "valley-b") {
253 t.Fatalf("flush --remote valley-a: %v %s", err, out)
254 }
255
256 // valley-b is back, and two flushes race for its spool.
257 os.Remove(filepath.Join(recv, "git@valley-b.down"))
258 var wg sync.WaitGroup
259 for i := 0; i < 2; i++ {
260 wg.Add(1)
261 go func() {
262 defer wg.Done()
263 if _, err := flushSpool(spoolB, true); err != nil {
264 t.Error(err)
265 }
266 }()
267 }
268 wg.Wait()
269 if out, err := tele(a, "flush"); err != nil || !strings.Contains(out, "0 records sent to ssh://git@valley-b") {
270 t.Fatalf("a last flush: %v %s", err, out)
271 }
272
273 want := map[string][]string{
274 "git@valley-a": {runA, runA + "-checks"},
275 "git@valley-b": {runB, runB + "-checks", runA2},
276 }
277 texts := map[string]string{"git@valley-a": "output of app", "git@valley-b": "output of site"}
278 for dest, runs := range want {
279 got := received(t, recv, dest)
280 seen := map[string]bool{}
281 for _, r := range got {
282 if seen[r.ClientID] {
283 t.Errorf("%s received %s twice", dest, r.ClientID)
284 }
285 seen[r.ClientID] = true
286 ok := false
287 for _, run := range runs {
288 ok = ok || r.Run == run
289 }
290 if !ok {
291 t.Errorf("%s received run %s's %s", dest, r.Run, r.Type)
292 }
293 if text, _ := r.Data["text"].(string); r.Type == "check.output" && !strings.Contains(text, texts[dest]) {
294 t.Errorf("%s received output %q", dest, text)
295 }
296 }
297 for _, run := range runs {
298 found := false
299 for _, r := range got {
300 found = found || r.Run == run
301 }
302 if !found {
303 t.Errorf("%s never received run %s", dest, run)
304 }
305 }
306 }
307 if n := len(received(t, recv, "git@valley-a")); n != 4 {
308 t.Errorf("valley-a received %d records, want approve.start, approve.checks, check.output and approve.end", n)
309 }
310
311 // The spool of an older CLI named no destination: it is kept, said,
312 // and never sent.
313 legacy, _ := legacySpool()
314 if _, err := (&telemetry.Stream{Dir: legacy}).Append(&telemetry.Record{Type: "approve.start", Time: telemetry.Stamp(time.Now()), Run: "rlegacy"}); err != nil {
315 t.Fatal(err)
316 }
317 before := len(received(t, recv, "git@valley-a")) + len(received(t, recv, "git@valley-b"))
318 if out, err := tele(a, "flush"); err != nil || !strings.Contains(out, "never sent") {
319 t.Fatalf("flush with a legacy spool: %v %s", err, out)
320 }
321 if after := len(received(t, recv, "git@valley-a")) + len(received(t, recv, "git@valley-b")); after != before {
322 t.Fatal("the legacy spool was sent")
323 }
324 // Emitting into a directory that is no bound spool stores nothing.
325 emit(a, legacy, "rlegacy", "approve.end")
326 if rng, _ := (&telemetry.Stream{Dir: legacy}).Range(); rng.Last != 1 {
327 t.Fatalf("the legacy spool took a record: %+v", rng)
328 }
329}
330
331// The spools stay bounded: a fifth destination finds no room while four
332// hold records to send or were used within the hour, and takes the place
333// of one that has sent everything and lain idle.
334func TestTheSpoolsAreBounded(t *testing.T) {
335 t.Setenv("XDG_STATE_HOME", t.TempDir())
336 var dirs []string
337 for i := 0; i < maxSpools; i++ {
338 dir, err := bindSpool(sshDest{host: fmt.Sprintf("git@valley-%d", i)})
339 if err != nil {
340 t.Fatal(err)
341 }
342 dirs = append(dirs, dir)
343 }
344 if _, err := bindSpool(sshDest{host: "git@valley-x"}); err == nil || !regexp.MustCompile(`not recorded`).MatchString(err.Error()) {
345 t.Fatalf("a fifth spool: %v", err)
346 }
347 old := time.Now().Add(-2 * idleAfter)
348 entries, _ := os.ReadDir(dirs[0])
349 for _, e := range entries {
350 os.Chtimes(filepath.Join(dirs[0], e.Name()), old, old)
351 }
352 if _, err := bindSpool(sshDest{host: "git@valley-x"}); err != nil {
353 t.Fatalf("a fifth spool beside an idle one: %v", err)
354 }
355 if _, err := os.Stat(dirs[0]); !os.IsNotExist(err) {
356 t.Fatalf("the idle spool is still there: %v", err)
357 }
358 if _, err := bindSpool(sshDest{host: "git@valley-1"}); err != nil {
359 t.Fatalf("an existing spool: %v", err)
360 }
361}