package web
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"craftdesign.group/quarry/internal/ops"
)
// The merge page with no pair named, on the shape of a large mirror: a
// few hundred open branches and a default pair whose conflict report
// names 20,000 files. Only the ops are stubs, with the shapes the real
// ones answer; the handler, remarshal, the meld and the render are the
// real path.
type mpIn struct {
Repo string `json:"repo" path:"repo"`
Branch string `json:"branch"`
Onto string `json:"onto"`
Summary bool `json:"summary"`
}
type mpSide struct {
Blob string `json:"blob,omitempty"`
Lines []string `json:"lines,omitempty"`
}
type mpRegion struct {
Kind string `json:"kind"`
Base reportSpan `json:"base"`
Ours reportSpan `json:"ours"`
Theirs reportSpan `json:"theirs"`
}
type mpFile struct {
Path string `json:"path"`
Kind string `json:"kind"`
Ours mpSide `json:"ours"`
Theirs mpSide `json:"theirs"`
Base mpSide `json:"base"`
Regions []mpRegion `json:"regions,omitempty"`
Omitted string `json:"omitted,omitempty"`
}
// mpAny lets a stub answer any shape, which marshals as itself.
type mpAny struct{ V any }
func (a mpAny) MarshalJSON() ([]byte, error) { return json.Marshal(a.V) }
type mpOut struct {
Branch string `json:"branch"`
Target string `json:"target"`
BranchTip string `json:"branchTip"`
TargetTip string `json:"targetTip"`
Verdict string `json:"verdict"`
Total int `json:"total"`
Omitted int `json:"omitted,omitempty"`
Files []mpFile `json:"files"`
Checkin bool `json:"checkin,omitempty"`
Protected bool `json:"protected"`
Owners []string `json:"owners,omitempty"`
MayJoin bool `json:"mayJoin"`
Behind int `json:"behind,omitempty"`
}
// mpReport is a conflicting pair of n files, the way pairConflicts shapes
// it: the first maxConflictFiles drawn with lines and regions, the rest
// named with their blobs.
func mpReport(branch, target string, n, nlines int) mpOut {
out := mpOut{Branch: branch, Target: target, BranchTip: "b" + branch, TargetTip: "t" + target,
Verdict: "conflict", Total: n, Omitted: max(0, n-250)}
lines := func(tag string) []string {
ls := make([]string, nlines)
for i := range ls {
ls[i] = fmt.Sprintf("func %s%d(x int) int { return x + %d } // %s", "f", i, i, tag)
}
return ls
}
for i := 0; i < min(n, 250); i++ {
f := mpFile{Path: fmt.Sprintf("drivers/net/dir%03d/file%05d.c", i%400, i), Kind: "text",
Ours: mpSide{Blob: fmt.Sprintf("o%06d", i)}, Theirs: mpSide{Blob: fmt.Sprintf("t%06d", i)}, Base: mpSide{Blob: fmt.Sprintf("a%06d", i)}}
if i < 20 {
f.Ours.Lines, f.Theirs.Lines, f.Base.Lines = lines("o"), lines("t"), lines("a")
k := nlines / 3
f.Regions = []mpRegion{
{Kind: "same", Base: reportSpan{0, k}, Ours: reportSpan{0, k}, Theirs: reportSpan{0, k}},
{Kind: "conflict", Base: reportSpan{k, k + 2}, Ours: reportSpan{k, k + 2}, Theirs: reportSpan{k, k + 2}},
{Kind: "same", Base: reportSpan{k + 2, nlines}, Ours: reportSpan{k + 2, nlines}, Theirs: reportSpan{k + 2, nlines}},
}
} else {
f.Omitted = "past the file limit"
}
out.Files = append(out.Files, f)
}
return out
}
// mpRegistry stubs the ops the page reads. tips returns the pair's
// current tips, so a test can move one between requests.
// mpConflictCalls counts merge.conflicts calls, so a test can say the
// page did not ask.
var mpConflictCalls atomic.Int32
func mpRegistry(tb testing.TB, files, nlines int, readOnly bool, tips func() (string, string)) *ops.Registry {
tb.Helper()
r := ops.NewRegistry()
reg := func(name, route string, run func(ctx context.Context, in mpIn) (any, error)) {
wrapped := func(ctx context.Context, in mpIn) (mpAny, error) {
v, err := run(ctx, in)
return mpAny{v}, err
}
caps := "o"
if !strings.Contains(route, "{repo}") {
caps = ""
}
if err := ops.Register(r, ops.Op[mpIn, mpAny]{Name: name, Caps: caps, Doc: "test stub", Kind: ops.Query,
Auth: ops.Anonymous, Route: route, Run: wrapped}); err != nil {
tb.Fatal(err)
}
}
rep := mpReport("feat-000", "trunk", files, nlines)
reg("meta.version", "GET /api/v1/version", func(context.Context, mpIn) (any, error) {
return map[string]string{"version": "t"}, nil
})
reg("repo.get", "GET /api/v1/r/{repo}", func(context.Context, mpIn) (any, error) {
if !readOnly {
return map[string]any{}, nil
}
return map[string]any{"mirror": map[string]any{"tracking": true, "url": "https://up.example.net/r/lib"}}, nil
})
reg("repo.counts", "GET /api/v1/r/{repo}/counts", func(context.Context, mpIn) (any, error) { return map[string]any{}, nil })
reg("timeline.list", "GET /api/v1/r/{repo}/timeline", func(context.Context, mpIn) (any, error) {
return map[string]any{"defaultBranch": "trunk"}, nil
})
reg("branch.list", "GET /api/v1/r/{repo}/branches", func(context.Context, mpIn) (any, error) {
rows := []branchRow{{Name: "trunk", Tip: "ttrunk", Date: "2026-11-10T00:00:00Z"}}
for i := 0; i < 200; i++ {
day := 10 - i/20
if day < 1 {
day = 1
}
rows = append(rows, branchRow{Name: fmt.Sprintf("feat-%03d", i), Tip: fmt.Sprintf("bfeat-%03d", i),
Date: fmt.Sprintf("2026-%02d-%02dT00:00:00Z", 11-i/60, day)})
}
return map[string]any{"branches": rows}, nil
})
reg("merge.conflicts", "GET /api/v1/r/{repo}/merge", func(ctx context.Context, in mpIn) (any, error) {
mpConflictCalls.Add(1)
out := rep
if tips != nil {
out.BranchTip, out.TargetTip = tips()
}
if in.Summary {
out.Files = []mpFile{}
}
out.MayJoin = ops.User(ctx) != ""
return out, nil
})
reg("landing.list", "GET /api/v1/r/{repo}/landings", func(context.Context, mpIn) (any, error) {
return map[string]any{"landings": []any{}}, nil
})
reg("checkin.mergebase", "GET /api/v1/r/{repo}/mergebase", func(context.Context, mpIn) (any, error) {
return map[string]any{"base": "abc"}, nil
})
return r
}
func mpGet(tb testing.TB, h http.Handler, target string, headers ...string) string {
tb.Helper()
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", target, nil)
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
h.ServeHTTP(w, req)
if w.Code != 200 {
tb.Fatalf("FAIL: %s answered %d: %.300s", target, w.Code, w.Body.String())
}
return w.Body.String()
}
func BenchmarkMergePageRepeat20kFiles(b *testing.B) {
h := HandlerWith(mpRegistry(b, 20000, 1500, false, nil), nil, nil, nil)
if body := mpGet(b, h, "/r/big/merge"); !strings.Contains(body, `data-hook="merge-page"`) {
b.Fatalf("FAIL: not the merge page: %.300s", body)
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
mpGet(b, h, "/r/big/merge")
}
}