gunk-dev/the-valley

telemetry_test.go

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