gunk-dev/the-valley

telemetry_test.go

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