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