gunk-dev/the-valley

telemetry_test.go

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