| 1 | package forge |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "testing" |
| 12 | ) |
| 13 | |
| 14 | // fakeHub is a repository on a hub: the task branch, the default branch |
| 15 | // and whether the task's commit landed on it. |
| 16 | type fakeHub struct { |
| 17 | mu sync.Mutex |
| 18 | head string |
| 19 | landed bool |
| 20 | merge string |
| 21 | // unborn: the default branch has no commits yet (an empty |
| 22 | // repository): no tip, and its name is not advertised. |
| 23 | unborn bool |
| 24 | requests []MergeRequest |
| 25 | // answer decides the hub's reply; it may land the merge first. |
| 26 | answer func(h *fakeHub, req MergeRequest) (MergeResult, error) |
| 27 | } |
| 28 | |
| 29 | func (h *fakeHub) inspect(context.Context) (RemoteState, error) { |
| 30 | h.mu.Lock() |
| 31 | defer h.mu.Unlock() |
| 32 | if h.unborn { |
| 33 | return RemoteState{Head: h.head, Default: "main", Unborn: true}, nil |
| 34 | } |
| 35 | return RemoteState{Head: h.head, Default: "main", Tip: strings.Repeat("9", 40), Landed: h.landed, MergeSHA: h.merge}, nil |
| 36 | } |
| 37 | |
| 38 | func (h *fakeHub) request(_ context.Context, req MergeRequest) (MergeResult, error) { |
| 39 | h.mu.Lock() |
| 40 | defer h.mu.Unlock() |
| 41 | h.requests = append(h.requests, req) |
| 42 | return h.answer(h, req) |
| 43 | } |
| 44 | |
| 45 | // mergeNow lands the merge like the hub does: a merge commit, the branch |
| 46 | // deleted. |
| 47 | func mergeNow(h *fakeHub, req MergeRequest) (MergeResult, error) { |
| 48 | if h.landed { |
| 49 | return MergeResult{Status: 409, Reason: "up_to_date"}, nil |
| 50 | } |
| 51 | if h.head != req.ExpectSHA { |
| 52 | return MergeResult{Status: 409, Reason: "moved"}, nil |
| 53 | } |
| 54 | h.landed, h.merge, h.head = true, strings.Repeat("8", 40), "" |
| 55 | return MergeResult{Status: 200, Merged: true, SHA: h.merge, Into: "main", BranchClosed: true}, nil |
| 56 | } |
| 57 | |
| 58 | func newMerge(t *testing.T, h *fakeHub) BranchMerge { |
| 59 | return BranchMerge{Root: t.TempDir(), Repo: "amadan.net/oficina/sample", Branch: "equipo/tk1-fix-typo", Commit: strings.Repeat("a", 40), Task: "tk1", Message: "Fix typo", Strategy: "merge", |
| 60 | Agent: AgentMeta{Session: "equipo-tk1", Harness: "equipo", Host: "test"}, Person: "p@example.com", Owners: []string{"p@example.com"}, |
| 61 | Inspect: h.inspect, Request: h.request, Confirm: func(context.Context) error { return nil }} |
| 62 | } |
| 63 | |
| 64 | func TestMergeBranch(t *testing.T) { |
| 65 | h := &fakeHub{head: strings.Repeat("a", 40), answer: mergeNow} |
| 66 | m := newMerge(t, h) |
| 67 | out, err := MergeBranch(context.Background(), m) |
| 68 | if err != nil || out.SHA != strings.Repeat("8", 40) || out.Into != "main" || out.Strategy != "merge" || out.Reconciled { |
| 69 | t.Fatalf("merge %+v %v", out, err) |
| 70 | } |
| 71 | if len(h.requests) != 1 || h.requests[0].ExpectSHA != m.Commit || h.requests[0].Strategy != "merge" || h.requests[0].KeepBranch || h.requests[0].Agent.Session != "equipo-tk1" { |
| 72 | t.Fatalf("request %+v", h.requests) |
| 73 | } |
| 74 | // Again (a retry, a restarted runner): the record answers, no request. |
| 75 | again, err := MergeBranch(context.Background(), m) |
| 76 | if err != nil || again.SHA != out.SHA || len(h.requests) != 1 { |
| 77 | t.Fatalf("again %+v %v (%d requests)", again, err, len(h.requests)) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | // TestMergeBranchReconcilesALostAnswer: the hub merged but its answer |
| 82 | // never arrived; the default branch shows the merge and no second request |
| 83 | // is ever sent. |
| 84 | func TestMergeBranchReconcilesALostAnswer(t *testing.T) { |
| 85 | h := &fakeHub{head: strings.Repeat("a", 40), answer: func(h *fakeHub, req MergeRequest) (MergeResult, error) { |
| 86 | mergeNow(h, req) |
| 87 | return MergeResult{}, ErrMergeUncertain |
| 88 | }} |
| 89 | m := newMerge(t, h) |
| 90 | out, err := MergeBranch(context.Background(), m) |
| 91 | if err != nil || !out.Reconciled || out.SHA != strings.Repeat("8", 40) || out.Into != "main" || len(h.requests) != 1 { |
| 92 | t.Fatalf("reconciled %+v %v (%d requests)", out, err, len(h.requests)) |
| 93 | } |
| 94 | if _, err := MergeBranch(context.Background(), m); err != nil || len(h.requests) != 1 { |
| 95 | t.Fatalf("a second request after reconcile: %v %d", err, len(h.requests)) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | // TestMergeBranchRecoversACrash: the runner died after recording the |
| 100 | // request. If the merge landed, the next call reads it from the default |
| 101 | // branch without asking; if it never reached the hub, it asks once. |
| 102 | func TestMergeBranchRecoversACrash(t *testing.T) { |
| 103 | for _, landed := range []bool{true, false} { |
| 104 | h := &fakeHub{head: strings.Repeat("a", 40), answer: mergeNow} |
| 105 | m := newMerge(t, h) |
| 106 | crashed := m |
| 107 | crashed.Request = func(ctx context.Context, req MergeRequest) (MergeResult, error) { |
| 108 | if landed { |
| 109 | h.mu.Lock() |
| 110 | mergeNow(h, req) |
| 111 | h.mu.Unlock() |
| 112 | } |
| 113 | return MergeResult{}, errors.New("process killed") |
| 114 | } |
| 115 | crashed.Inspect = func(ctx context.Context) (RemoteState, error) { |
| 116 | if rec, ok, _ := m.load(); ok && rec.Phase == mergeRequested { |
| 117 | // The process is gone before it could look again. |
| 118 | return RemoteState{}, errors.New("process killed") |
| 119 | } |
| 120 | return h.inspect(ctx) |
| 121 | } |
| 122 | if _, err := MergeBranch(context.Background(), crashed); !errors.Is(err, ErrMergeUncertain) { |
| 123 | t.Fatalf("crash: %v", err) |
| 124 | } |
| 125 | if rec, ok, _ := m.load(); !ok || rec.Phase != mergeRequested { |
| 126 | t.Fatalf("record before the request: %+v", rec) |
| 127 | } |
| 128 | out, err := MergeBranch(context.Background(), m) |
| 129 | if err != nil || out.SHA != strings.Repeat("8", 40) { |
| 130 | t.Fatalf("landed=%v recovery %+v %v", landed, out, err) |
| 131 | } |
| 132 | if want := map[bool]int{true: 0, false: 1}[landed]; len(h.requests) != want { |
| 133 | t.Fatalf("landed=%v: %d requests after the crash, want %d", landed, len(h.requests), want) |
| 134 | } |
| 135 | if out.Reconciled != landed { |
| 136 | t.Fatalf("landed=%v reconciled=%v", landed, out.Reconciled) |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | // TestMergeBranchNeverMergesAMovedBranch: a head other than the judged |
| 142 | // commit is never merged: refused before any request, and when it moves |
| 143 | // during the request the hub's refusal is reported as moved. |
| 144 | func TestMergeBranchNeverMergesAMovedBranch(t *testing.T) { |
| 145 | h := &fakeHub{head: strings.Repeat("b", 40), answer: mergeNow} |
| 146 | m := newMerge(t, h) |
| 147 | if _, err := MergeBranch(context.Background(), m); !errors.Is(err, ErrMergeMoved) || len(h.requests) != 0 { |
| 148 | t.Fatalf("moved: %v (%d requests)", err, len(h.requests)) |
| 149 | } |
| 150 | h.head = "" |
| 151 | if _, err := MergeBranch(context.Background(), m); !errors.Is(err, ErrMergeMoved) || len(h.requests) != 0 { |
| 152 | t.Fatalf("gone: %v", err) |
| 153 | } |
| 154 | h.head = m.Commit |
| 155 | m.beforeRequest = func() { h.mu.Lock(); h.head = strings.Repeat("c", 40); h.mu.Unlock() } |
| 156 | if _, err := MergeBranch(context.Background(), m); !errors.Is(err, ErrMergeMoved) || h.landed { |
| 157 | t.Fatalf("moved during the request: %v landed=%v", err, h.landed) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | func TestMergeBranchRefusals(t *testing.T) { |
| 162 | for _, c := range []struct { |
| 163 | res MergeResult |
| 164 | want error |
| 165 | }{ |
| 166 | {MergeResult{Status: 409, Reason: "conflicts"}, ErrMergeConflict}, |
| 167 | {MergeResult{Status: 409, Reason: "ci_not_green", CIState: "running"}, ErrMergeCIPending}, |
| 168 | {MergeResult{Status: 409, Reason: "ci_not_green", CIState: "pending"}, ErrMergeCIPending}, |
| 169 | {MergeResult{Status: 409, Reason: "ci_not_green", CIState: "failure"}, ErrMergeCIFailed}, |
| 170 | {MergeResult{Status: 403}, ErrMergeForbidden}, |
| 171 | {MergeResult{Status: 404}, ErrMergeForbidden}, |
| 172 | {MergeResult{Status: 409, Reason: "archived"}, ErrMergeFailed}, |
| 173 | {MergeResult{Status: 502, Reason: "internal"}, ErrMergeUncertain}, |
| 174 | } { |
| 175 | h := &fakeHub{head: strings.Repeat("a", 40), answer: func(*fakeHub, MergeRequest) (MergeResult, error) { return c.res, nil }} |
| 176 | m := newMerge(t, h) |
| 177 | if _, err := MergeBranch(context.Background(), m); !errors.Is(err, c.want) { |
| 178 | t.Fatalf("%+v: %v, want %v", c.res, err, c.want) |
| 179 | } |
| 180 | // A refusal is final for this request only: a later call asks again. |
| 181 | h.answer = mergeNow |
| 182 | if out, err := MergeBranch(context.Background(), m); err != nil || out.SHA == "" || len(h.requests) != 2 { |
| 183 | t.Fatalf("after %+v: %+v %v", c.res, out, err) |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | func TestMergeBranchRefusesInvalid(t *testing.T) { |
| 189 | h := &fakeHub{head: strings.Repeat("a", 40), answer: mergeNow} |
| 190 | for name, mut := range map[string]func(*BranchMerge){ |
| 191 | "default branch": func(m *BranchMerge) { m.Branch = "main" }, |
| 192 | "not a task": func(m *BranchMerge) { m.Branch = "feature/x" }, |
| 193 | "short sha": func(m *BranchMerge) { m.Commit = "abc" }, |
| 194 | "other person": func(m *BranchMerge) { m.Person = "q@example.com" }, |
| 195 | "strategy": func(m *BranchMerge) { m.Strategy = "rebase" }, |
| 196 | "no session": func(m *BranchMerge) { m.Agent.Session = "" }, |
| 197 | "repository": func(m *BranchMerge) { m.Repo = "github.com/x/y" }, |
| 198 | "no lease": func(m *BranchMerge) { m.Confirm = nil }, |
| 199 | } { |
| 200 | m := newMerge(t, h) |
| 201 | mut(&m) |
| 202 | if _, err := MergeBranch(context.Background(), m); !errors.Is(err, ErrMergeRefused) { |
| 203 | t.Fatalf("%s: %v", name, err) |
| 204 | } |
| 205 | } |
| 206 | // The lease is confirmed right before the request: without it, nothing. |
| 207 | m := newMerge(t, h) |
| 208 | m.Confirm = func(context.Context) error { return errors.New("superseded") } |
| 209 | if _, err := MergeBranch(context.Background(), m); !errors.Is(err, ErrMergeUncertain) || len(h.requests) != 0 { |
| 210 | t.Fatalf("without the lease: %v (%d requests)", err, len(h.requests)) |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | func TestHubMerge(t *testing.T) { |
| 215 | var got struct { |
| 216 | path, auth string |
| 217 | body map[string]any |
| 218 | } |
| 219 | answer := func(w http.ResponseWriter) { |
| 220 | w.WriteHeader(200) |
| 221 | w.Write([]byte(`{"merged":true,"sha":"` + strings.Repeat("8", 40) + `","into":"main","branch_closed":true}`)) |
| 222 | } |
| 223 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 224 | got.path, got.auth = r.URL.EscapedPath(), r.Header.Get("Authorization") |
| 225 | json.NewDecoder(r.Body).Decode(&got.body) |
| 226 | answer(w) |
| 227 | })) |
| 228 | defer srv.Close() |
| 229 | cred := Credential{Agent: "equipo~p@example.com", Bearer: "token-1"} |
| 230 | req := MergeRequest{ExpectSHA: strings.Repeat("a", 40), Message: "Fix typo", Strategy: "merge", Agent: AgentMeta{Session: "equipo-tk1", Harness: "equipo", Host: "docs-t1"}} |
| 231 | res, err := HubMerge(context.Background(), srv.Client(), srv.URL, cred, "amadan.net/oficina/sample", "equipo/tk1-fix-typo", req) |
| 232 | if err != nil || !res.Merged || res.SHA != strings.Repeat("8", 40) || res.Into != "main" || !res.BranchClosed { |
| 233 | t.Fatalf("%+v %v", res, err) |
| 234 | } |
| 235 | if got.path != "/api/v1/repos/oficina/sample/branches/equipo%2Ftk1-fix-typo/merge" || got.auth != "Bearer token-1" { |
| 236 | t.Fatalf("request %s %q", got.path, got.auth) |
| 237 | } |
| 238 | if got.body["expect_sha"] != req.ExpectSHA || got.body["strategy"] != "merge" || got.body["keep_branch"] != false || got.body["agent"].(map[string]any)["session"] != "equipo-tk1" { |
| 239 | t.Fatalf("body %+v", got.body) |
| 240 | } |
| 241 | for _, c := range []struct { |
| 242 | status int |
| 243 | body string |
| 244 | merged bool |
| 245 | err error |
| 246 | reason string |
| 247 | }{ |
| 248 | {200, `{"merged":true}`, false, nil, ""}, |
| 249 | {200, `not json`, false, ErrMergeUncertain, ""}, |
| 250 | {500, `oops`, false, ErrMergeUncertain, ""}, |
| 251 | {409, `{"error":"x","reason":"ci_not_green","ci_state":"running"}`, false, nil, "ci_not_green"}, |
| 252 | {403, `{"error":"you must be a writer on this repo to do that"}`, false, nil, ""}, |
| 253 | } { |
| 254 | answer = func(w http.ResponseWriter) { w.WriteHeader(c.status); w.Write([]byte(c.body)) } |
| 255 | res, err := HubMerge(context.Background(), srv.Client(), srv.URL, cred, "amadan.net/oficina/sample", "equipo/tk1-fix-typo", req) |
| 256 | if res.Merged != c.merged || !errors.Is(err, c.err) || res.Reason != c.reason || err == nil && res.Status != c.status { |
| 257 | t.Fatalf("%d %s: %+v %v", c.status, c.body, res, err) |
| 258 | } |
| 259 | } |
| 260 | } |
| 261 | |