package thin import ( "context" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "os" "os/exec" "path/filepath" "strings" "testing" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/wire" ) // pushForge is a bare remote on disk; fail makes the next pushes fail. type pushForge struct { Forge dir string fail int } func (f *pushForge) Remote(context.Context, string, Use) (workspace.Remote, error) { if f.fail > 0 { f.fail-- return workspace.Remote{}, errors.New("hub unavailable") } return workspace.Remote{URL: f.dir}, nil } // relayRig: a remote with main at base, a worker's commit on base that // the remote has never seen (its one-commit pack), and a primary's // Engineer and Relay over local state. type relayRig struct { e *Engineer f *pushForge relay *Relay base, commit string pack []byte pushes string confirm error // seed is the work tree the remote was cloned from; remote the bare // remote; root the rig's directory. seed, remote, root string } const relayBranch = "equipo/tk1-swipe-back" func newRelayRig(t *testing.T) *relayRig { return newRelayRigWith(t, nil) } // newRelayRigWith is newRelayRig whose worker commit also writes extra. func newRelayRigWith(t *testing.T, extra map[string]string) *relayRig { return newRelayRigFiles(t, nil, extra, nil) } // newRelayRigFiles is newRelayRig whose base also has the files before, // and whose worker commit also writes extra and moves files (git mv). func newRelayRigFiles(t *testing.T, before, extra map[string]string, moves [][2]string) *relayRig { t.Helper() root := t.TempDir() seed := filepath.Join(root, "seed") gitOut(t, root, "init", "-q", "-b", "main", seed) os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = false\n"), 0644) for name, text := range before { os.WriteFile(filepath.Join(seed, name), []byte(text), 0644) } gitOut(t, seed, "add", "-A") gitOut(t, seed, "commit", "-q", "-m", "base") base := gitOut(t, seed, "rev-parse", "HEAD") remote := filepath.Join(root, "remote.git") gitOut(t, root, "clone", "-q", "--bare", seed, remote) pushes := filepath.Join(root, "pushes") hook := filepath.Join(remote, "hooks", "post-receive") os.WriteFile(hook, []byte("#!/bin/sh\ncat >> "+pushes+"\n"), 0755) // The worker's commit, made elsewhere on the base. os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = true\n"), 0644) for name, text := range extra { os.WriteFile(filepath.Join(seed, name), []byte(text), 0644) } for _, m := range moves { gitOut(t, seed, "mv", m[0], m[1]) } gitOut(t, seed, "add", "-A") gitOut(t, seed, "commit", "-q", "-m", "swipe back") commit := gitOut(t, seed, "rev-parse", "HEAD") list := exec.Command("git", "-C", seed, "rev-list", "--objects", "--no-walk", commit) objects, _ := list.Output() packer := exec.Command("git", "-C", seed, "pack-objects", "--stdout", "-q") packer.Stdin = strings.NewReader(string(objects)) pack, err := packer.Output() if err != nil { t.Fatal(err) } os.MkdirAll(filepath.Join(root, "state"), 0700) os.MkdirAll(filepath.Join(root, "work"), 0700) s, err := OpenState(context.Background(), filepath.Join(root, "state")) if err != nil { t.Fatal(err) } t.Cleanup(func() { s.Close() }) f := &pushForge{dir: remote} r := &relayRig{f: f, base: base, commit: commit, pack: pack, pushes: pushes, seed: seed, remote: remote, root: root} e := &Engineer{Clones: &Clones{Root: filepath.Join(root, "work"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{"p@x"}, Host: "test"} 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 e.ConfirmPublication = func(context.Context, string, int64, string) error { return r.confirm } r.e, r.relay = e, &Relay{State: s, Engine: e} return r } func (r *relayRig) header() wire.TransferHeader { 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} } func (r *relayRig) receive(t *testing.T, pack []byte, h wire.TransferHeader) { t.Helper() sum := sha256.Sum256(pack) 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 { t.Fatal(err) } } func (r *relayRig) publish(t *testing.T, id string) { t.Helper() h := r.header() 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 { t.Fatal(err) } } // reports are the published reports in the outbox. func (r *relayRig) reports(t *testing.T) []wire.PublishedReport { t.Helper() frames, _, err := r.e.O.State.Unacked(context.Background(), 0) if err != nil { t.Fatal(err) } var out []wire.PublishedReport for _, f := range frames { if f.Type == wire.FramePublished { var p wire.PublishedReport json.Unmarshal(f.Data, &p) out = append(out, p) } } return out } func (r *relayRig) pushCount() int { raw, _ := os.ReadFile(r.pushes) return strings.Count(string(raw), "refs/heads/"+relayBranch) } func (r *relayRig) head(t *testing.T) string { out, _ := exec.Command("git", "--git-dir="+r.f.dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+relayBranch).Output() return strings.TrimSpace(string(out)) } // The primary publishes a worker's commit from its pack: indexed beside // the clone, the branch pushed at exactly the commit, then published. func TestRelayPublishesAWorkersCommit(t *testing.T) { r := newRelayRig(t) r.receive(t, r.pack, r.header()) r.publish(t, "pb_1") r.relay.Once(context.Background()) reps := r.reports(t) if len(reps) != 1 || !reps[0].Pushed || reps[0].CandidateSHA != r.commit || r.head(t) != r.commit || r.pushCount() != 1 { t.Fatalf("reports %+v head %s pushes %d", reps, r.head(t), r.pushCount()) } // Run again: nothing more. r.relay.Once(context.Background()) if len(r.reports(t)) != 1 || r.pushCount() != 1 { t.Fatal("published twice") } } // A failed push is reported (not pushed); Retry's new publication of the // same commit pushes it once, from the commit kept for it. func TestRelayRetryAfterPushFailure(t *testing.T) { r := newRelayRig(t) r.receive(t, r.pack, r.header()) r.publish(t, "pb_1") if err := r.e.Clones.Ensure(context.Background(), "amadan.net/oficina/sample"); err != nil { t.Fatal(err) } r.f.fail = 10 r.relay.Once(context.Background()) reps := r.reports(t) if len(reps) != 1 || reps[0].Pushed || reps[0].Reason != "push_failed" || r.pushCount() != 0 { t.Fatalf("after a failed push %+v", reps) } r.f.fail = 0 r.publish(t, "pb_2") r.relay.Once(context.Background()) reps = r.reports(t) if len(reps) != 2 || !reps[1].Pushed || reps[1].Publication != "pb_2" || r.head(t) != r.commit || r.pushCount() != 1 { t.Fatalf("republish %+v pushes %d", reps, r.pushCount()) } } // SIGKILLed after indexing and before the push: restarted, it pushes // exactly once. SIGKILLed after the push and before published: restarted, // it reconciles from the remote and reports pushed without pushing again. func TestRelayCrashes(t *testing.T) { defer func() { relayFault = nil }() for _, point := range []string{"indexed", "pushed"} { t.Run(point, func(t *testing.T) { r := newRelayRig(t) r.receive(t, r.pack, r.header()) r.publish(t, "pb_1") relayFault = func(p string) bool { return p == point } r.relay.Once(context.Background()) relayFault = nil if len(r.reports(t)) != 0 { t.Fatal("reported before the crash point") } // A new process over the same state and directories. again := &Relay{State: r.e.O.State, Engine: r.e} again.Once(context.Background()) reps := r.reports(t) if len(reps) != 1 || !reps[0].Pushed || r.head(t) != r.commit || r.pushCount() != 1 { t.Fatalf("after restart %+v pushes %d", reps, r.pushCount()) } }) } } // Cancel after the pack arrived and before the push: the instance refuses // the confirmation, nothing is pushed, the publication reports cancelled. func TestRelayCancelledBeforePush(t *testing.T) { r := newRelayRig(t) r.receive(t, r.pack, r.header()) r.publish(t, "pb_1") r.confirm = ErrWithdrawn r.relay.Once(context.Background()) reps := r.reports(t) if len(reps) != 1 || reps[0].Pushed || reps[0].Reason != "cancelled" || r.pushCount() != 0 || r.head(t) != "" { t.Fatalf("cancelled %+v pushes %d head %s", reps, r.pushCount(), r.head(t)) } } // A pack that is not the worker's commit on the dispatched base is never // pushed: another commit under the header, or a commit on another base. func TestRelayRefusesAWrongCommit(t *testing.T) { r := newRelayRig(t) // The transfer and the publication agree, but the commit's parent is // not the base they name. h := r.header() h.BaseSHA = strings.Repeat("e", 40) r.receive(t, r.pack, h) 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 { t.Fatal(err) } r.relay.Once(context.Background()) reps := r.reports(t) if len(reps) != 1 || reps[0].Pushed || reps[0].Reason != "candidate_unavailable" || r.pushCount() != 0 { t.Fatalf("wrong commit %+v", reps) } } // A pack too large to relay is declared by a chunk count past the shared // bound, which the instance refuses at once; the worker refuses it too. func TestRelayDeclaresOversize(t *testing.T) { r := newRelayRig(t) h := r.header() if err := r.e.O.State.AcceptUpload(context.Background(), "up-1", wire.SendPackCommand{Transfer: h, Have: []string{}}); err != nil { t.Fatal(err) } big := make([]byte, wire.MaxTransferBytes+10) if err := r.e.O.State.queueUpload(context.Background(), h, big); err != nil { t.Fatal(err) } frames, _, _ := r.e.O.State.Unacked(context.Background(), 0) if len(frames) != 1 { t.Fatalf("%d chunks for an oversized pack", len(frames)) } var b wire.Blob json.Unmarshal(frames[0].Data, &b) if b.Total <= wire.MaxTransferChunks { t.Fatalf("declared total %d is within the bound %d", b.Total, wire.MaxTransferChunks) } if err := r.e.O.State.AcceptChunk(context.Background(), "in-1", b); err != nil { t.Fatal(err) } if _, err := r.e.O.State.pack(context.Background(), h); !errors.Is(err, errPackRefused) { t.Fatalf("the receiver took a declared oversize: %v", err) } }