| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/base64" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 17 | "amadan.net/oficina/equipo/internal/wire" |
| 18 | ) |
| 19 | |
| 20 | // pushForge is a bare remote on disk; fail makes the next pushes fail. |
| 21 | type pushForge struct { |
| 22 | Forge |
| 23 | dir string |
| 24 | fail int |
| 25 | } |
| 26 | |
| 27 | func (f *pushForge) Remote(context.Context, string, Use) (workspace.Remote, error) { |
| 28 | if f.fail > 0 { |
| 29 | f.fail-- |
| 30 | return workspace.Remote{}, errors.New("hub unavailable") |
| 31 | } |
| 32 | return workspace.Remote{URL: f.dir}, nil |
| 33 | } |
| 34 | |
| 35 | // relayRig: a remote with main at base, a worker's commit on base that |
| 36 | // the remote has never seen (its one-commit pack), and a primary's |
| 37 | // Engineer and Relay over local state. |
| 38 | type relayRig struct { |
| 39 | e *Engineer |
| 40 | f *pushForge |
| 41 | relay *Relay |
| 42 | base, commit string |
| 43 | pack []byte |
| 44 | pushes string |
| 45 | confirm error |
| 46 | // seed is the work tree the remote was cloned from; remote the bare |
| 47 | // remote; root the rig's directory. |
| 48 | seed, remote, root string |
| 49 | } |
| 50 | |
| 51 | const relayBranch = "equipo/tk1-swipe-back" |
| 52 | |
| 53 | func newRelayRig(t *testing.T) *relayRig { return newRelayRigWith(t, nil) } |
| 54 | |
| 55 | // newRelayRigWith is newRelayRig whose worker commit also writes extra. |
| 56 | func newRelayRigWith(t *testing.T, extra map[string]string) *relayRig { |
| 57 | return newRelayRigFiles(t, nil, extra, nil) |
| 58 | } |
| 59 | |
| 60 | // newRelayRigFiles is newRelayRig whose base also has the files before, |
| 61 | // and whose worker commit also writes extra and moves files (git mv). |
| 62 | func newRelayRigFiles(t *testing.T, before, extra map[string]string, moves [][2]string) *relayRig { |
| 63 | t.Helper() |
| 64 | root := t.TempDir() |
| 65 | seed := filepath.Join(root, "seed") |
| 66 | gitOut(t, root, "init", "-q", "-b", "main", seed) |
| 67 | os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = false\n"), 0644) |
| 68 | for name, text := range before { |
| 69 | os.WriteFile(filepath.Join(seed, name), []byte(text), 0644) |
| 70 | } |
| 71 | gitOut(t, seed, "add", "-A") |
| 72 | gitOut(t, seed, "commit", "-q", "-m", "base") |
| 73 | base := gitOut(t, seed, "rev-parse", "HEAD") |
| 74 | remote := filepath.Join(root, "remote.git") |
| 75 | gitOut(t, root, "clone", "-q", "--bare", seed, remote) |
| 76 | pushes := filepath.Join(root, "pushes") |
| 77 | hook := filepath.Join(remote, "hooks", "post-receive") |
| 78 | os.WriteFile(hook, []byte("#!/bin/sh\ncat >> "+pushes+"\n"), 0755) |
| 79 | // The worker's commit, made elsewhere on the base. |
| 80 | os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = true\n"), 0644) |
| 81 | for name, text := range extra { |
| 82 | os.WriteFile(filepath.Join(seed, name), []byte(text), 0644) |
| 83 | } |
| 84 | for _, m := range moves { |
| 85 | gitOut(t, seed, "mv", m[0], m[1]) |
| 86 | } |
| 87 | gitOut(t, seed, "add", "-A") |
| 88 | gitOut(t, seed, "commit", "-q", "-m", "swipe back") |
| 89 | commit := gitOut(t, seed, "rev-parse", "HEAD") |
| 90 | list := exec.Command("git", "-C", seed, "rev-list", "--objects", "--no-walk", commit) |
| 91 | objects, _ := list.Output() |
| 92 | packer := exec.Command("git", "-C", seed, "pack-objects", "--stdout", "-q") |
| 93 | packer.Stdin = strings.NewReader(string(objects)) |
| 94 | pack, err := packer.Output() |
| 95 | if err != nil { |
| 96 | t.Fatal(err) |
| 97 | } |
| 98 | os.MkdirAll(filepath.Join(root, "state"), 0700) |
| 99 | os.MkdirAll(filepath.Join(root, "work"), 0700) |
| 100 | s, err := OpenState(context.Background(), filepath.Join(root, "state")) |
| 101 | if err != nil { |
| 102 | t.Fatal(err) |
| 103 | } |
| 104 | t.Cleanup(func() { s.Close() }) |
| 105 | f := &pushForge{dir: remote} |
| 106 | r := &relayRig{f: f, base: base, commit: commit, pack: pack, pushes: pushes, seed: seed, remote: remote, root: root} |
| 107 | e := &Engineer{Clones: &Clones{Root: filepath.Join(root, "work"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{"p@x"}, Host: "test"} |
| 108 | e.O.Runner.GitPath, e.O.Runner.WorkspaceRoot, e.O.Runner.StateDir, e.O.State = "/usr/bin/git", filepath.Join(root, "work"), filepath.Join(root, "state"), s |
| 109 | e.ConfirmPublication = func(context.Context, string, int64, string) error { return r.confirm } |
| 110 | r.e, r.relay = e, &Relay{State: s, Engine: e} |
| 111 | return r |
| 112 | } |
| 113 | |
| 114 | func (r *relayRig) header() wire.TransferHeader { |
| 115 | return wire.TransferHeader{ID: "tr_1", Direction: wire.TransferOutbound, Repo: "amadan.net/oficina/sample", TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: r.base, CandidateSHA: r.commit} |
| 116 | } |
| 117 | |
| 118 | func (r *relayRig) receive(t *testing.T, pack []byte, h wire.TransferHeader) { |
| 119 | t.Helper() |
| 120 | sum := sha256.Sum256(pack) |
| 121 | if err := r.e.O.State.AcceptChunk(context.Background(), "chunk-"+h.ID, wire.Blob{Transfer: h, Index: 0, Total: 1, SHA256: hex.EncodeToString(sum[:]), Data: base64.StdEncoding.EncodeToString(pack)}); err != nil { |
| 122 | t.Fatal(err) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | func (r *relayRig) publish(t *testing.T, id string) { |
| 127 | t.Helper() |
| 128 | h := r.header() |
| 129 | if err := r.e.O.State.AcceptPublish(context.Background(), "pub-"+id, wire.PublishCommand{Publication: id, TaskID: h.TaskID, StepID: h.StepID, Attempt: h.Attempt, Repo: h.Repo, Branch: relayBranch, Person: "p@x", BaseSHA: r.base, CandidateSHA: r.commit, Transfer: h.ID}); err != nil { |
| 130 | t.Fatal(err) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | // reports are the published reports in the outbox. |
| 135 | func (r *relayRig) reports(t *testing.T) []wire.PublishedReport { |
| 136 | t.Helper() |
| 137 | frames, _, err := r.e.O.State.Unacked(context.Background(), 0) |
| 138 | if err != nil { |
| 139 | t.Fatal(err) |
| 140 | } |
| 141 | var out []wire.PublishedReport |
| 142 | for _, f := range frames { |
| 143 | if f.Type == wire.FramePublished { |
| 144 | var p wire.PublishedReport |
| 145 | json.Unmarshal(f.Data, &p) |
| 146 | out = append(out, p) |
| 147 | } |
| 148 | } |
| 149 | return out |
| 150 | } |
| 151 | |
| 152 | func (r *relayRig) pushCount() int { |
| 153 | raw, _ := os.ReadFile(r.pushes) |
| 154 | return strings.Count(string(raw), "refs/heads/"+relayBranch) |
| 155 | } |
| 156 | |
| 157 | func (r *relayRig) head(t *testing.T) string { |
| 158 | out, _ := exec.Command("git", "--git-dir="+r.f.dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+relayBranch).Output() |
| 159 | return strings.TrimSpace(string(out)) |
| 160 | } |
| 161 | |
| 162 | // The primary publishes a worker's commit from its pack: indexed beside |
| 163 | // the clone, the branch pushed at exactly the commit, then published. |
| 164 | func TestRelayPublishesAWorkersCommit(t *testing.T) { |
| 165 | r := newRelayRig(t) |
| 166 | r.receive(t, r.pack, r.header()) |
| 167 | r.publish(t, "pb_1") |
| 168 | r.relay.Once(context.Background()) |
| 169 | reps := r.reports(t) |
| 170 | if len(reps) != 1 || !reps[0].Pushed || reps[0].CandidateSHA != r.commit || r.head(t) != r.commit || r.pushCount() != 1 { |
| 171 | t.Fatalf("reports %+v head %s pushes %d", reps, r.head(t), r.pushCount()) |
| 172 | } |
| 173 | // Run again: nothing more. |
| 174 | r.relay.Once(context.Background()) |
| 175 | if len(r.reports(t)) != 1 || r.pushCount() != 1 { |
| 176 | t.Fatal("published twice") |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | // A failed push is reported (not pushed); Retry's new publication of the |
| 181 | // same commit pushes it once, from the commit kept for it. |
| 182 | func TestRelayRetryAfterPushFailure(t *testing.T) { |
| 183 | r := newRelayRig(t) |
| 184 | r.receive(t, r.pack, r.header()) |
| 185 | r.publish(t, "pb_1") |
| 186 | if err := r.e.Clones.Ensure(context.Background(), "amadan.net/oficina/sample"); err != nil { |
| 187 | t.Fatal(err) |
| 188 | } |
| 189 | r.f.fail = 10 |
| 190 | r.relay.Once(context.Background()) |
| 191 | reps := r.reports(t) |
| 192 | if len(reps) != 1 || reps[0].Pushed || reps[0].Reason != "push_failed" || r.pushCount() != 0 { |
| 193 | t.Fatalf("after a failed push %+v", reps) |
| 194 | } |
| 195 | r.f.fail = 0 |
| 196 | r.publish(t, "pb_2") |
| 197 | r.relay.Once(context.Background()) |
| 198 | reps = r.reports(t) |
| 199 | if len(reps) != 2 || !reps[1].Pushed || reps[1].Publication != "pb_2" || r.head(t) != r.commit || r.pushCount() != 1 { |
| 200 | t.Fatalf("republish %+v pushes %d", reps, r.pushCount()) |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // SIGKILLed after indexing and before the push: restarted, it pushes |
| 205 | // exactly once. SIGKILLed after the push and before published: restarted, |
| 206 | // it reconciles from the remote and reports pushed without pushing again. |
| 207 | func TestRelayCrashes(t *testing.T) { |
| 208 | defer func() { relayFault = nil }() |
| 209 | for _, point := range []string{"indexed", "pushed"} { |
| 210 | t.Run(point, func(t *testing.T) { |
| 211 | r := newRelayRig(t) |
| 212 | r.receive(t, r.pack, r.header()) |
| 213 | r.publish(t, "pb_1") |
| 214 | relayFault = func(p string) bool { return p == point } |
| 215 | r.relay.Once(context.Background()) |
| 216 | relayFault = nil |
| 217 | if len(r.reports(t)) != 0 { |
| 218 | t.Fatal("reported before the crash point") |
| 219 | } |
| 220 | // A new process over the same state and directories. |
| 221 | again := &Relay{State: r.e.O.State, Engine: r.e} |
| 222 | again.Once(context.Background()) |
| 223 | reps := r.reports(t) |
| 224 | if len(reps) != 1 || !reps[0].Pushed || r.head(t) != r.commit || r.pushCount() != 1 { |
| 225 | t.Fatalf("after restart %+v pushes %d", reps, r.pushCount()) |
| 226 | } |
| 227 | }) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | // Cancel after the pack arrived and before the push: the instance refuses |
| 232 | // the confirmation, nothing is pushed, the publication reports cancelled. |
| 233 | func TestRelayCancelledBeforePush(t *testing.T) { |
| 234 | r := newRelayRig(t) |
| 235 | r.receive(t, r.pack, r.header()) |
| 236 | r.publish(t, "pb_1") |
| 237 | r.confirm = ErrWithdrawn |
| 238 | r.relay.Once(context.Background()) |
| 239 | reps := r.reports(t) |
| 240 | if len(reps) != 1 || reps[0].Pushed || reps[0].Reason != "cancelled" || r.pushCount() != 0 || r.head(t) != "" { |
| 241 | t.Fatalf("cancelled %+v pushes %d head %s", reps, r.pushCount(), r.head(t)) |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | // A pack that is not the worker's commit on the dispatched base is never |
| 246 | // pushed: another commit under the header, or a commit on another base. |
| 247 | func TestRelayRefusesAWrongCommit(t *testing.T) { |
| 248 | r := newRelayRig(t) |
| 249 | // The transfer and the publication agree, but the commit's parent is |
| 250 | // not the base they name. |
| 251 | h := r.header() |
| 252 | h.BaseSHA = strings.Repeat("e", 40) |
| 253 | r.receive(t, r.pack, h) |
| 254 | if err := r.e.O.State.AcceptPublish(context.Background(), "pub-x", wire.PublishCommand{Publication: "pb_x", TaskID: "tk1", StepID: "s1", Attempt: 1, Repo: h.Repo, Branch: relayBranch, Person: "p@x", BaseSHA: h.BaseSHA, CandidateSHA: r.commit, Transfer: "tr_1"}); err != nil { |
| 255 | t.Fatal(err) |
| 256 | } |
| 257 | r.relay.Once(context.Background()) |
| 258 | reps := r.reports(t) |
| 259 | if len(reps) != 1 || reps[0].Pushed || reps[0].Reason != "candidate_unavailable" || r.pushCount() != 0 { |
| 260 | t.Fatalf("wrong commit %+v", reps) |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | // A pack too large to relay is declared by a chunk count past the shared |
| 265 | // bound, which the instance refuses at once; the worker refuses it too. |
| 266 | func TestRelayDeclaresOversize(t *testing.T) { |
| 267 | r := newRelayRig(t) |
| 268 | h := r.header() |
| 269 | if err := r.e.O.State.AcceptUpload(context.Background(), "up-1", wire.SendPackCommand{Transfer: h, Have: []string{}}); err != nil { |
| 270 | t.Fatal(err) |
| 271 | } |
| 272 | big := make([]byte, wire.MaxTransferBytes+10) |
| 273 | if err := r.e.O.State.queueUpload(context.Background(), h, big); err != nil { |
| 274 | t.Fatal(err) |
| 275 | } |
| 276 | frames, _, _ := r.e.O.State.Unacked(context.Background(), 0) |
| 277 | if len(frames) != 1 { |
| 278 | t.Fatalf("%d chunks for an oversized pack", len(frames)) |
| 279 | } |
| 280 | var b wire.Blob |
| 281 | json.Unmarshal(frames[0].Data, &b) |
| 282 | if b.Total <= wire.MaxTransferChunks { |
| 283 | t.Fatalf("declared total %d is within the bound %d", b.Total, wire.MaxTransferChunks) |
| 284 | } |
| 285 | if err := r.e.O.State.AcceptChunk(context.Background(), "in-1", b); err != nil { |
| 286 | t.Fatal(err) |
| 287 | } |
| 288 | if _, err := r.e.O.State.pack(context.Background(), h); !errors.Is(err, errPackRefused) { |
| 289 | t.Fatalf("the receiver took a declared oversize: %v", err) |
| 290 | } |
| 291 | } |
| 292 | |