gunk-dev/the-valley

telemetry_test.go

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