gunk-dev/the-valley

telemetry_test.go

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