gunk-dev/the-valley

telemetry_test.go

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