gunk-dev/the-valley

server_test.go

sourcec0b8faba075dmain's published tip history
88.8 KiB
1package server
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "crypto/sha256"
8 "encoding/base64"
9 "errors"
10 "fmt"
11 "io"
12 "net"
13 "net/http"
14 "net/http/httptest"
15 "os"
16 "os/exec"
17 "path/filepath"
18 "regexp"
19 "runtime"
20 "slices"
21 "strings"
22 "sync"
23 "sync/atomic"
24 "syscall"
25 "testing"
26 "time"
27
28 "the-valley/knot"
29 "the-valley/web/export"
30 "the-valley/web/export/exporttest"
31)
32
33// harness is a server over a real store that the fixture's export was
34// uploaded to, with a clock the test sets.
35type harness struct {
36 t *testing.T
37 f *exporttest.Fixture
38 store *export.Store
39 srv *Server
40 now time.Time
41}
42
43// newHarness serves the fixture's export, two minutes after it was
44// collected.
45func newHarness(t *testing.T) *harness {
46 t.Helper()
47 f := exporttest.New(t)
48 store, err := export.OpenStore(t.TempDir(), func(err error) { t.Errorf("the store reported: %v", err) })
49 if err != nil {
50 t.Fatal(err)
51 }
52 f.Upload(t, store)
53 h := &harness{t: t, f: f, store: store, now: exporttest.Collected.Add(2 * time.Minute)}
54 h.srv = New(Config{Store: store, Now: func() time.Time { return h.now },
55 Log: func(err error) { t.Errorf("the server logged: %v", err) }})
56 return h
57}
58
59func (h *harness) do(method, target string) *httptest.ResponseRecorder {
60 h.t.Helper()
61 w := httptest.NewRecorder()
62 h.srv.ServeHTTP(w, httptest.NewRequest(method, target, nil))
63 return w
64}
65
66func (h *harness) get(target string) *httptest.ResponseRecorder {
67 h.t.Helper()
68 return h.do("GET", target)
69}
70
71// page is the body of a GET that must answer 200.
72func (h *harness) page(target string) string {
73 h.t.Helper()
74 w := h.get(target)
75 if w.Code != http.StatusOK {
76 h.t.Fatalf("GET %s answered %d:\n%s", target, w.Code, w.Body)
77 }
78 return w.Body.String()
79}
80
81// tip is the fixture's published source tip of app.
82func (h *harness) tip() string { return h.f.Export.Projects[0].SourceTip }
83
84// publish activates a new generation, signed at: the fixture's export
85// changed by change, with the bundles given, by project, in place of the
86// fixture's.
87func (h *harness) publish(at time.Time, bundles map[string]string, change func(*export.Export)) export.Generation {
88 t := h.t
89 t.Helper()
90 e, err := export.Decode(h.f.ExportJSON)
91 if err != nil {
92 t.Fatal(err)
93 }
94 change(e)
95 data, err := e.Encode()
96 if err != nil {
97 t.Fatal(err)
98 }
99 paths := map[string]string{}
100 for _, p := range e.Projects {
101 if paths[p.Name] = bundles[p.Name]; paths[p.Name] == "" {
102 paths[p.Name] = h.f.Bundles[p.Name]
103 }
104 }
105 bodies := map[string]export.Body{}
106 for name, path := range paths {
107 if bodies[name], err = export.FileBody(name, path); err != nil {
108 t.Fatal(err)
109 }
110 }
111 m, err := export.NewManifest(exporttest.Instance, exporttest.Destination, at.UnixNano(), e, data, bodies)
112 if err != nil {
113 t.Fatal(err)
114 }
115 hw, err := h.store.HighWater()
116 if err != nil {
117 t.Fatal(err)
118 }
119 a := h.f.Admission()
120 a.Now, a.HighWater = at.Add(time.Second), hw
121 if m, err = export.VerifyManifest(bytes.NewReader(h.f.Sign(t, m)), a); err != nil {
122 t.Fatal(err)
123 }
124 st, err := h.store.Stage(context.Background(), m)
125 if err != nil {
126 t.Fatal(err)
127 }
128 inv, err := h.store.Inventory(st)
129 if err != nil {
130 t.Fatal(err)
131 }
132 for _, need := range inv.Needs {
133 body := data
134 if need.Name != export.ExportFile {
135 if body, err = os.ReadFile(paths[need.Name]); err != nil {
136 t.Fatal(err)
137 }
138 }
139 req := httptest.NewRequest("PUT", export.BodyPath(m.Sequence, need.SHA256), bytes.NewReader(body))
140 if _, err := export.StageBody(st.Bodies(), export.Body{Name: need.Name, SHA256: need.SHA256, Size: need.Size}, 64<<20, req); err != nil {
141 t.Fatal(err)
142 }
143 }
144 g, err := h.store.Activate(context.Background(), st)
145 if err != nil {
146 t.Fatal(err)
147 }
148 return g
149}
150
151// active is the generation the store serves.
152func (h *harness) active() export.Generation {
153 h.t.Helper()
154 g, release, err := h.store.Open()
155 if err != nil {
156 h.t.Fatal(err)
157 }
158 release()
159 return g
160}
161
162// git runs git on the repository at repo, with no configuration of the
163// caller's and a fixed identity for the commits it writes.
164func git(t *testing.T, repo string, stdin []byte, args ...string) string {
165 t.Helper()
166 cmd := exec.Command(export.GitProgram, append([]string{"--git-dir=" + repo}, args...)...)
167 for _, kv := range os.Environ() {
168 if !strings.HasPrefix(kv, "GIT_") {
169 cmd.Env = append(cmd.Env, kv)
170 }
171 }
172 cmd.Env = append(cmd.Env, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
173 "GIT_AUTHOR_NAME=Example Author", "GIT_AUTHOR_EMAIL=author@example.org", "GIT_AUTHOR_DATE=1791190800 +0000",
174 "GIT_COMMITTER_NAME=Example Author", "GIT_COMMITTER_EMAIL=author@example.org", "GIT_COMMITTER_DATE=1791190800 +0000")
175 if stdin != nil {
176 cmd.Stdin = bytes.NewReader(stdin)
177 }
178 var out, stderr bytes.Buffer
179 cmd.Stdout, cmd.Stderr = &out, &stderr
180 if err := exporttest.Run(t, cmd, 2*time.Minute); err != nil {
181 t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, stderr.String())
182 }
183 return strings.TrimSpace(out.String())
184}
185
186// section is the part of a page from one marker up to the next.
187func section(t *testing.T, page, from, to string) string {
188 t.Helper()
189 i := strings.Index(page, from)
190 j := strings.Index(page[max(i, 0):], to)
191 if i < 0 || j < 0 {
192 t.Fatalf("the page has no section from %q to %q", from, to)
193 }
194 return page[i : i+j]
195}
196
197// The plan page keeps the template's reading order, says what free to
198// start means, shows the ready changes as one card in no order, and
199// shows how old the export is.
200func TestPlanPage(t *testing.T) {
201 h := newHarness(t)
202 page := h.page("/")
203
204 at := -1
205 for _, heading := range []string{">Waiting on you<", ">In flight<", ">Paths<", ">Milestones<"} {
206 i := strings.Index(page, heading)
207 if i <= at {
208 t.Fatalf("%s is not where the reading order puts it", heading)
209 }
210 at = i
211 }
212 for _, want := range []string{
213 "free to start: an open, unclaimed, unblocked outcome or bug",
214 "Nothing here waits on you.",
215 "Ready changes — order not assessed",
216 `<span class="handle">kmno</span>`, "plan: list the milestones", "app v2", "approved · integrator: stale",
217 "Collected 2026-10-25 12:00 UTC, 2 minutes ago",
218 "claimed by agent 2 hours ago",
219 "in progress, unclaimed",
220 "Readers browse the app&#39;s plan", "1 of 5 done",
221 "Unfiled", "Render Markdown in a later slice",
222 `<span class="chip blocked">waits on oc-a000002, a knot in an unpublished project</span>`,
223 } {
224 if !strings.Contains(page, want) {
225 t.Errorf("the plan page does not show %q", want)
226 }
227 }
228 if strings.Count(page, "Ready changes") != 1 {
229 t.Error("the ready changes are not one card")
230 }
231
232 // The bug nobody claims and nothing blocks is free to start.
233 if !strings.Contains(page, `<i class="k ready" role="img" aria-label="free to start" title="free to start"></i><span class="body"><a class="id" href="/app/knots/bd-a000004">`) {
234 t.Error("bd-a000004 is not shown as free to start")
235 }
236
237 // The milestone's path puts oc-a000003 after the knot it waits on.
238 paths := section(t, page, `id="paths-h"`, `id="ms-h"`)
239 second := strings.Index(paths, `<span class="stage-num">2</span>`)
240 if second < 0 || strings.Index(paths, "oc-a000002") > second || strings.Index(paths, "oc-a000003") < second {
241 t.Errorf("the path does not order oc-a000003 after oc-a000002:\n%s", paths)
242 }
243
244 // Nothing of the hidden project is linked or named, and nothing is
245 // fetched from another origin.
246 for _, want := range []string{"lands in an unpublished project", "lands in a knot in an unpublished project"} {
247 if !strings.Contains(page, want) {
248 t.Errorf("the plan page does not show %q", want)
249 }
250 }
251 for _, unwanted := range append([]string{"/site/knots/", "/site/source/", "http://", "https://", `class="chip stale"`}, unpublishedText...) {
252 if strings.Contains(page, unwanted) {
253 t.Errorf("the plan page holds %q", unwanted)
254 }
255 }
256
257 h.now = exporttest.Collected.Add(6 * time.Minute)
258 page = h.page("/")
259 if !strings.Contains(page, `Collected 2026-10-25 12:00 UTC, 6 minutes ago <span class="chip stale">stale</span>`) {
260 t.Error("an export six minutes old is not marked stale")
261 }
262}
263
264// A blocked knot's chip names the published knots it waits on, and says
265// once that it also waits on unpublished work, naming nothing of it:
266// oc-a000003 waits on oc-a000002 and on a knot of the hidden site, which
267// the export leaves out of waiting_on and marks with waiting_on_hidden.
268// A knot waiting on unpublished work alone says only that. An export
269// without the field, as v1 exports before it, is read, and its chip
270// names what waiting_on holds.
271func TestWaitsOnChip(t *testing.T) {
272 h := newHarness(t)
273 chip := func(text string) string { return `<span class="chip blocked">waits on ` + text + `</span>` }
274 cases := []struct {
275 name string
276 change func(*export.Knot)
277 want string
278 }{
279 {"a published and an unpublished blocker", func(*export.Knot) {}, "oc-a000002, a knot in an unpublished project"},
280 {"two published blockers and an unpublished one", func(k *export.Knot) { k.WaitingOn = append(k.WaitingOn, "oc-a000006") },
281 "oc-a000002, oc-a000006, a knot in an unpublished project"},
282 {"an unpublished blocker alone", func(k *export.Knot) { k.WaitingOn = []string{} }, "a knot in an unpublished project"},
283 {"an export without waiting_on_hidden", func(k *export.Knot) { k.WaitingOnHidden = false }, "oc-a000002"},
284 }
285 for i, c := range cases {
286 t.Run(c.name, func(t *testing.T) {
287 h.publish(exporttest.SignedAt.Add(time.Duration(i+1)*time.Minute), nil, func(e *export.Export) {
288 for j := range e.Projects[0].Knots {
289 if k := &e.Projects[0].Knots[j]; k.ID == "oc-a000003" {
290 if !k.WaitingOnHidden {
291 t.Fatal("the fixture's oc-a000003 does not carry waiting_on_hidden")
292 }
293 c.change(k)
294 }
295 }
296 })
297 page := h.page("/")
298 if !strings.Contains(page, chip(c.want)) {
299 t.Errorf("the plan page does not show %q:\n%s", chip(c.want), section(t, page, `id="ms-h"`, "</body>"))
300 }
301 if n := strings.Count(page, `<span class="chip blocked">`); n != 1 {
302 t.Errorf("the plan page shows %d blocked chips", n)
303 }
304 for _, unwanted := range unpublishedText {
305 if strings.Contains(page, unwanted) {
306 t.Errorf("the plan page holds %q", unwanted)
307 }
308 }
309 })
310 }
311}
312
313// unpublishedText is what of the hidden project site the fixture's
314// references hold: its name and its knots' IDs. No page shows any of it.
315var unpublishedText = []string{"site:", "oc-b000001", "oc-b000002", "lands in site", ">site<", "valley:site"}
316
317// A knot's page shows its body and comments, and marks the edited
318// comment. A reference into a hidden project is shown as unpublished,
319// with nothing of its text, and a missing knot of a public project is
320// named as missing.
321func TestKnotPage(t *testing.T) {
322 h := newHarness(t)
323 page := h.page("/app/knots/oc-a000002")
324 for _, want := range []string{
325 "Each milestone is listed with its progress.",
326 "Start with the milestones that have open children.",
327 "Claimed; the change is ready for approval.",
328 `<span class="chip quiet">edited</span><span>2026-10-25 10:30 UTC by agent</span>`,
329 `<a href="/app/knots/oc-a000001">Readers browse the app&#39;s plan</a>`,
330 } {
331 if !strings.Contains(page, want) {
332 t.Errorf("the knot's page does not show %q", want)
333 }
334 }
335 if n := strings.Count(page, ">edited<"); n != 1 {
336 t.Errorf("%d comments are marked edited; one was edited", n)
337 }
338
339 page = h.page("/app/knots/oc-a000003")
340 if !strings.Contains(page, `<a href="/app/knots/oc-a000002">The plan page lists milestones</a>`) {
341 t.Error("the local blocker is not linked")
342 }
343 for _, want := range []string{
344 `<span class="nochild"></span><span class="t"><span class="muted">a knot in an unpublished project</span></span>`,
345 "<dt>Lands in</dt><dd>an unpublished project</dd>",
346 } {
347 if !strings.Contains(page, want) {
348 t.Errorf("the knot's page does not show %q", want)
349 }
350 }
351 page += h.page("/app/knots/bd-a000004")
352 if !strings.Contains(page, "<dt>Lands in</dt><dd>a knot in an unpublished project</dd>") {
353 t.Error("a target in the hidden project is not shown as unpublished")
354 }
355 for _, unwanted := range append([]string{"/site/knots/", "/site/source/"}, unpublishedText...) {
356 if strings.Contains(page, unwanted) {
357 t.Errorf("the knot's page shows %q", unwanted)
358 }
359 }
360 if w := h.get("/app/knots/oc-fffffff"); w.Code != http.StatusNotFound {
361 t.Errorf("a missing knot answered %d", w.Code)
362 }
363
364 // A knot of a public project the graph does not hold, and a local
365 // knot that is not there, are named as missing. A change of the
366 // hidden project is not named.
367 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
368 for i := range e.Projects[0].Knots {
369 if k := &e.Projects[0].Knots[i]; k.ID == "oc-a000003" {
370 k.BlockedBy = append(k.BlockedBy, "app:oc-fffffff", "oc-eeeeeee")
371 k.Edges = append(k.Edges, export.Edge{Field: "blocked_by", Ref: "app:oc-fffffff", Project: "app", ID: "oc-fffffff", State: export.EdgeDangling})
372 k.Changes = append(k.Changes, "valley:site/kmnopqrstuvwxyzkmnopqrstuvwxyzkm", "valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm")
373 }
374 }
375 })
376 page = h.page("/app/knots/oc-a000003")
377 for _, want := range []string{
378 `<span class="mono">app:oc-fffffff</span> <span class="muted">not found in its graph</span>`,
379 `<span class="mono">oc-eeeeeee</span> <span class="muted">not found</span>`,
380 `<li class="mono">a change in an unpublished project</li>`,
381 `<li class="mono">valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm</li>`,
382 } {
383 if !strings.Contains(page, want) {
384 t.Errorf("the knot's page does not show %q", want)
385 }
386 }
387 for _, unwanted := range unpublishedText {
388 if strings.Contains(page, unwanted) {
389 t.Errorf("the knot's page shows %q", unwanted)
390 }
391 }
392}
393
394// A project the export does not hold as public answers every route
395// exactly as a project that does not exist, even when its repository is
396// in the generation's directory.
397func TestHiddenProjectAnswersLikeMissing(t *testing.T) {
398 h := newHarness(t)
399 g := h.active()
400 if err := os.CopyFS(filepath.Join(g.Dir, "repos", "site.git"), os.DirFS(h.f.Repos["site"])); err != nil {
401 t.Fatal(err)
402 }
403 siteTip := git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef)
404 notFound := h.get("/app/knots/oc-fffffff")
405 for _, route := range []string{
406 "/%s",
407 "/%s/",
408 "/%s/knots/oc-b000001",
409 "/%s/source",
410 "/%s/source/",
411 "/%s/source/tree/" + siteTip + "/",
412 "/%s/source/blob/" + siteTip + "/README.md",
413 "/%s/source/log/" + siteTip,
414 "/%s/source/tree/" + siteTip + "/no/such/path/",
415 "/%s/source/anything",
416 } {
417 hidden, missing := h.get(fmt.Sprintf(route, "site")), h.get(fmt.Sprintf(route, "nosuch"))
418 if hidden.Code != http.StatusNotFound || missing.Code != http.StatusNotFound {
419 t.Errorf("%s answered %d hidden and %d missing", route, hidden.Code, missing.Code)
420 }
421 if fmt.Sprint(hidden.Header()) != fmt.Sprint(missing.Header()) {
422 t.Errorf("%s answered with other headers hidden than missing:\n%v\n%v", route, hidden.Header(), missing.Header())
423 }
424 if !bytes.Equal(hidden.Body.Bytes(), missing.Body.Bytes()) || !bytes.Equal(hidden.Body.Bytes(), notFound.Body.Bytes()) {
425 t.Errorf("%s answered with another page hidden than missing", route)
426 }
427 }
428}
429
430// A project's name may be any word the server's routes use: source,
431// knots, or web-export, the receiver's first segment. Each such project
432// is served on every route, and /<project>/ redirects to its tree. The
433// server's own paths, under /-/, are never a project's.
434func TestProjectNamesBesideTheServersPaths(t *testing.T) {
435 for _, name := range []string{"source", "knots", "web-export"} {
436 t.Run(name, func(t *testing.T) {
437 h := newHarness(t)
438 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{name: h.f.Bundles["app"]},
439 func(e *export.Export) { e.Projects[0].Name = name })
440 tip := h.tip()
441 tree := "/" + name + "/source/tree/" + tip + "/"
442 if plan := h.page("/"); !strings.Contains(plan, `href="/`+name+`/knots/oc-a000002"`) {
443 t.Errorf("the plan page does not link %s's knots", name)
444 }
445 for _, target := range []string{
446 "/" + name + "/knots/oc-a000002",
447 tree,
448 "/" + name + "/source/blob/" + tip + "/docs/guide.md",
449 "/" + name + "/source/log/" + tip,
450 } {
451 h.page(target)
452 }
453 for _, target := range []string{"/" + name + "/", "/" + name, "/" + name + "/source/"} {
454 if w := h.get(target); w.Code != http.StatusFound || w.Header().Get("Location") != tree {
455 t.Errorf("GET %s answered %d to %q, not a redirect to %s", target, w.Code, w.Header().Get("Location"), tree)
456 }
457 }
458 for _, target := range []string{
459 "/-", "/-/", "/-/" + name + "/", "/-/knots/oc-a000002", "/-/source/tree/" + tip + "/",
460 "/-/" + name + "/source/tree/" + tip + "/", "/app/", "/site/", "/site",
461 } {
462 if w := h.get(target); w.Code != http.StatusNotFound {
463 t.Errorf("GET %s answered %d, not 404", target, w.Code)
464 }
465 }
466 })
467 }
468}
469
470// A source route serves a commit only when main's published tip reaches
471// it, and refuses every other object ID or name with the one 404.
472func TestUnreachableCommitIsRefused(t *testing.T) {
473 h := newHarness(t)
474 repo, _ := h.active().Repo("app")
475 tip := h.tip()
476 tree := git(t, repo, nil, "rev-parse", tip+"^{tree}")
477 readme := git(t, repo, nil, "rev-parse", tip+":README.md")
478 side := git(t, repo, nil, "commit-tree", tree, "-p", tip, "-m", "a commit main does not reach")
479 parent := git(t, repo, nil, "rev-parse", tip+"~2")
480 notFound := h.get("/app/knots/oc-fffffff").Body.String()
481
482 for _, commit := range []string{side, tree, readme, tip[:12], "main", "HEAD", strings.Repeat("0", 40), tip + "~1"} {
483 for _, route := range []string{"/app/source/tree/%s/", "/app/source/blob/%s/README.md", "/app/source/log/%s"} {
484 target := fmt.Sprintf(route, commit)
485 w := h.get(target)
486 if w.Code != http.StatusNotFound || w.Body.String() != notFound {
487 t.Errorf("GET %s answered %d, not the one 404", target, w.Code)
488 }
489 }
490 }
491
492 // A commit the tip reaches is served, as that commit had it.
493 page := h.page("/app/source/blob/" + parent + "/README.md")
494 if !strings.Contains(page, "A synthetic project for the web UI&#39;s tests.") || strings.Contains(page, "readme") {
495 t.Errorf("the first README is not served as the first commit had it:\n%s", page)
496 }
497}
498
499// The source browser lists a directory and its README, shows a file and
500// main's log, and every source link names its project, a full commit and
501// a path.
502func TestSourceBrowser(t *testing.T) {
503 h := newHarness(t)
504 tip := h.tip()
505
506 for _, path := range []string{"/app/source", "/app/source/"} {
507 w := h.get(path)
508 if w.Code != http.StatusFound || w.Header().Get("Location") != "/app/source/tree/"+tip+"/" {
509 t.Fatalf("the project's source answered %d to %q", w.Code, w.Header().Get("Location"))
510 }
511 }
512
513 root := h.page("/app/source/tree/" + tip + "/")
514 docs, src, readme := strings.Index(root, ">docs/<"), strings.Index(root, ">src/<"), strings.Index(root, ">README.md<")
515 if docs < 0 || src < 0 || readme < 0 || readme < src || src < docs {
516 t.Errorf("the root does not list docs/ and src/ before README.md:\n%s", root)
517 }
518 if !strings.Contains(root, `<pre class="text"># app`) {
519 t.Error("the root does not show its README")
520 }
521 if dir := h.page("/app/source/tree/" + tip + "/docs/"); !strings.Contains(dir, ">guide.md<") {
522 t.Error("docs/ does not list guide.md")
523 }
524 file := h.page("/app/source/blob/" + tip + "/docs/guide.md")
525 if !strings.Contains(file, `<tr id="L1"><td class="ln"><a href="#L1">1</a></td><td class="src"># Guide</td></tr>`) {
526 t.Errorf("the file is not shown line by line:\n%s", file)
527 }
528 log := h.page("/app/source/log/" + tip)
529 first, last := strings.Index(log, "docs: a guide, and the README names it"), strings.Index(log, "app: the first README")
530 if first < 0 || last < first {
531 t.Errorf("the log does not list main's commits newest first:\n%s", log)
532 }
533
534 links := regexp.MustCompile(`href="(/[^"]*/source/[^"]*)"`)
535 named := regexp.MustCompile(`^/app/source/(tree|blob|log)/[0-9a-f]{40}(/|$)`)
536 for _, page := range []string{root, file, log} {
537 for _, m := range links.FindAllStringSubmatch(page, -1) {
538 if !named.MatchString(m[1]) {
539 t.Errorf("the link %s names no commit", m[1])
540 }
541 }
542 }
543
544 for _, target := range []string{
545 "/app/source/tree/" + tip + "/README.md/",
546 "/app/source/blob/" + tip + "/docs",
547 "/app/source/blob/" + tip + "/docs/guide.md/",
548 "/app/source/blob/" + tip + "/docs/../README.md",
549 "/app/source/blob/" + tip + "/docs%2Fguide.md",
550 "/app/source/tree/" + tip + "//",
551 "/app/source/log/" + tip + "?from=" + strings.ToUpper(tip),
552 } {
553 if w := h.get(target); w.Code != http.StatusNotFound {
554 t.Errorf("GET %s answered %d", target, w.Code)
555 }
556 }
557}
558
559// file is one file a test commits: its mode, path and content.
560type file struct{ mode, path, content string }
561
562// commitMain writes a commit onto the fixture's app main, with message,
563// that holds the files given beside what main holds. It returns the new
564// tip and a bundle of it. Each content is written once, however many
565// files hold it.
566func (h *harness) commitMain(message string, files ...file) (tip, bundle string) {
567 t := h.t
568 t.Helper()
569 repo := h.f.Repos["app"]
570 var b bytes.Buffer
571 data := func(s string) { fmt.Fprintf(&b, "data %d\n%s\n", len(s), s) }
572 marks := map[string]int{}
573 for _, f := range files {
574 if _, ok := marks[f.content]; !ok {
575 marks[f.content] = len(marks) + 1
576 fmt.Fprintf(&b, "blob\nmark :%d\n", marks[f.content])
577 data(f.content)
578 }
579 }
580 who := "Example Author <author@example.org> 1791190800 +0000"
581 fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who)
582 data(message)
583 fmt.Fprintf(&b, "from %s\n", git(t, repo, nil, "rev-parse", export.MainRef))
584 for _, f := range files {
585 fmt.Fprintf(&b, "M %s :%d %s\n", f.mode, marks[f.content], f.path)
586 }
587 git(t, repo, b.Bytes(), "fast-import", "--quiet")
588 tip = git(t, repo, nil, "rev-parse", export.MainRef)
589 bundle = filepath.Join(t.TempDir(), "app.bundle")
590 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
591 return tip, bundle
592}
593
594// publishMain activates a generation whose app main is tip, carried by
595// bundle.
596func (h *harness) publishMain(at time.Time, tip, bundle string) {
597 h.t.Helper()
598 h.publish(at, map[string]string{"app": bundle}, func(e *export.Export) { e.Projects[0].SourceTip = tip })
599}
600
601// hostileMain writes a commit onto the fixture's app main that holds a
602// file of HTML, a file larger than a page shows, a binary file, a file
603// whose name is HTML, and a symbolic link out of the repository. It
604// returns the new tip and a bundle of it.
605func (h *harness) hostileMain() (tip, bundle string) {
606 return h.commitMain("hostile: <script>alert(\"subject\")</script>\n",
607 file{"100644", "page.html", "<html><script>alert(\"file\")</script><img src=x onerror=alert(2)></html>\n"},
608 file{"100644", "big.txt", strings.Repeat("big\n", (MaxFile/4)+1)},
609 file{"100644", "binary.bin", "\x7fELF\x00\x01\x02<script>alert(\"binary\")</script>"},
610 file{"100644", "<img src=x onerror=alert(3)>.txt", "named\n"},
611 file{"120000", "link", "../../etc/passwd"},
612 )
613}
614
615// HTML, scripts, large files and binary files from a repository or the
616// plan render inert: escaped as text, or not shown.
617func TestHostileContentRendersInert(t *testing.T) {
618 h := newHarness(t)
619 tip, bundle := h.hostileMain()
620 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
621 e.Projects[0].SourceTip = tip
622 })
623
624 inert := func(target, page string, wants ...string) {
625 t.Helper()
626 // Escaped, a tag is text; only a tag the page did not escape, or
627 // an attribute it let a value break out into, is active.
628 for _, active := range []string{"<script", "<img", `" onerror`, "\x00"} {
629 if strings.Contains(page, active) {
630 t.Errorf("GET %s holds %q", target, active)
631 }
632 }
633 for _, want := range wants {
634 if !strings.Contains(page, want) {
635 t.Errorf("GET %s does not show %q", target, want)
636 }
637 }
638 }
639 at := "/app/source/tree/" + tip + "/"
640 inert(at, h.page(at),
641 `&lt;script&gt;alert(&#34;readme&#34;)&lt;/script&gt;`,
642 `&lt;img src=x onerror=alert(3)&gt;.txt`,
643 `href="/app/source/blob/`+tip+`/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"`)
644 at = "/app/source/blob/" + tip + "/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"
645 inert(at, h.page(at), ">named<")
646 at = "/app/source/blob/" + tip + "/page.html"
647 inert(at, h.page(at), `&lt;html&gt;&lt;script&gt;alert(&#34;file&#34;)&lt;/script&gt;&lt;img src=x onerror=alert(2)&gt;&lt;/html&gt;`)
648 at = "/app/source/blob/" + tip + "/big.txt"
649 page := h.page(at)
650 inert(at, page, "This file is 1.0 MiB, larger than the 1.0 MiB a page shows.")
651 if len(page) > 64<<10 {
652 t.Errorf("the large file's page is %d bytes", len(page))
653 }
654 at = "/app/source/blob/" + tip + "/binary.bin"
655 inert(at, h.page(at), "This file is binary, 39 bytes, and is not shown.")
656 at = "/app/source/blob/" + tip + "/link"
657 inert(at, h.page(at), "A symbolic link to ../../etc/passwd. It is not followed.")
658 at = "/app/source/log/" + tip
659 inert(at, h.page(at), "hostile: &lt;script&gt;alert(&#34;subject&#34;)&lt;/script&gt;")
660
661 at = "/app/knots/bd-a000004"
662 inert(at, h.page(at),
663 `A README holding &lt;script&gt;alert(&#34;knot&#34;)&lt;/script&gt; must show as text.`,
664 `Also &lt;img src=x onerror=alert(1)&gt; in a comment.`)
665}
666
667// A directory larger than a page reads is listed in part, and a commit
668// message larger than a page reads ends its page of history early. git
669// is stopped once its listing passes MaxRead, and nothing past a record's
670// bound is kept.
671func TestOversizedTreeAndHistory(t *testing.T) {
672 h := newHarness(t)
673 // Each entry of huge/ takes 308 bytes of git ls-tree's output, so
674 // 15,000 of them pass MaxRead at about entry 13,600.
675 longest := "!" + strings.Repeat("l", 4095)
676 files := []file{{"100644", "huge/" + longest, "x\n"}}
677 name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) }
678 for i := range 15_000 {
679 files = append(files, file{"100644", "huge/" + name(i), "x\n"})
680 }
681 if n := 15_000 * (6 + 1 + 4 + 1 + 40 + 1 + 7 + 1 + 246 + 1); n <= MaxRead {
682 t.Fatalf("the listing of huge/ is %d bytes, within MaxRead", n)
683 }
684 h.commitMain("app: a directory larger than a page reads\n", files...)
685 h.commitMain("long: " + strings.Repeat("a long subject ", (100<<10)/15) + "\n")
686 tip, bundle := h.commitMain("longer: " + strings.Repeat("a subject past the bound ", (5<<20)/25) + "\n")
687 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
688
689 at := "/app/source/tree/" + tip + "/huge/"
690 page := h.page(at)
691 if !strings.Contains(page, "This directory is larger than a page reads, so only part of it is listed.") {
692 t.Error("huge/ is not marked as listed in part")
693 }
694 if n := strings.Count(page, `<tr><td class="name">`); n != MaxEntries {
695 t.Errorf("huge/ lists %d entries, not %d", n, MaxEntries)
696 }
697 if !strings.Contains(page, `">`+longest+`</a>`) {
698 t.Error("the entry with the longest name git accepts is not listed whole")
699 }
700 if len(page) > 1<<20 {
701 t.Errorf("huge/'s page is %d bytes", len(page))
702 }
703 if w := h.get("/app/source/blob/" + tip + "/huge/" + name(0)); w.Code != http.StatusOK {
704 t.Errorf("an entry read before MaxRead answered %d", w.Code)
705 }
706 if w := h.get("/app/source/blob/" + tip + "/huge/" + name(14_999)); w.Code != http.StatusNotFound {
707 t.Errorf("an entry past MaxRead answered %d", w.Code)
708 }
709
710 at = "/app/source/log/" + tip
711 page = h.page(at)
712 if !strings.Contains(page, "This page ends early: its commits are larger than a page reads.") {
713 t.Error("the page of history holding a 5 MiB message does not end early")
714 }
715 if n := strings.Count(page, `<tr><td class="name">`); n != 1 {
716 t.Errorf("the page that ends early lists %d commits, not the one it cut", n)
717 }
718 if m := regexp.MustCompile(`<td>(longer: a subject past the bound[^<]*)…</td>`).FindStringSubmatch(page); m == nil || len(m[1]) > maxLogText {
719 t.Error("the cut commit's subject is not shown cut to maxLogText")
720 }
721 older := at + "?from=" + git(t, h.f.Repos["app"], nil, "rev-parse", tip+"~1")
722 if !strings.Contains(page, `href="`+older+`"`) {
723 t.Error("the page that ends early does not link the commits after the one it cut")
724 }
725 page = h.page(older)
726 if strings.Contains(page, "ends early") || !strings.Contains(page, "long: a long subject") || !strings.Contains(page, "app: the first README") {
727 t.Errorf("the next page of history is not whole:\n%s", page)
728 }
729 if strings.Contains(page, strings.Repeat("a long subject ", (maxLogText/15)+1)) {
730 t.Error("a subject longer than a page shows is not cut")
731 }
732 for _, p := range []string{at, older} {
733 if n := len(h.page(p)); n > 64<<10 {
734 t.Errorf("GET %s is %d bytes", p, n)
735 }
736 }
737}
738
739// The directories along a path share one budget of MaxRead bytes of git
740// ls-tree's output. Each of big/ and big/zz/ lists about 3 MB before
741// the entry the path names next, within MaxRead alone, so the directory
742// big/zz/ is served. A path through both, to big/zz/zz/f, passes the
743// budget and answers 404. The directory's own listing has a budget of
744// its own.
745func TestResolveSharesOneBudget(t *testing.T) {
746 h := newHarness(t)
747 name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) }
748 var files []file
749 for i := range 10_000 {
750 files = append(files, file{"100644", "big/" + name(i), "x\n"}, file{"100644", "big/zz/" + name(i), "x\n"})
751 }
752 files = append(files, file{"100644", "big/zz/zz/f", "the file\n"})
753 if each := 6 + 1 + 4 + 1 + 40 + 1 + 246 + 1; 10_000*each > MaxRead || 2*10_000*each <= MaxRead {
754 t.Fatalf("the listings take %d bytes each, not between half MaxRead and MaxRead", 10_000*each)
755 }
756 tip, bundle := h.commitMain("app: two large directories, one in the other\n", files...)
757 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
758
759 h.page("/app/source/tree/" + tip + "/big/zz/")
760 h.page("/app/source/blob/" + tip + "/big/zz/" + name(0))
761 for _, target := range []string{"/app/source/tree/" + tip + "/big/zz/zz/", "/app/source/blob/" + tip + "/big/zz/zz/f"} {
762 if w := h.get(target); w.Code != http.StatusNotFound {
763 t.Errorf("GET %s, through %d bytes of listings, answered %d", target, 2*10_000*300, w.Code)
764 }
765 }
766}
767
768// lines writes onto the fixture's app main a merge of n lines of
769// history, each of length commits, all from main's tip. The lines' commits
770// are dated in turn, one line's after another's, so a log interleaves
771// them, and each page ends with commits of every line still to show. The
772// merge is an octopus when n is more than two. It returns the merge and a
773// bundle of it.
774func (h *harness) lines(n, length int) (tip, bundle string) {
775 var commits []commit
776 for i := range length {
777 for l := range n {
778 c := commit{message: fmt.Sprintf("line %d, commit %d\n", l, i), parents: []int{0}}
779 if i > 0 {
780 c.parents = []int{(i-1)*n + l + 1}
781 }
782 commits = append(commits, c)
783 }
784 }
785 merge := commit{message: fmt.Sprintf("merge %d lines\n", n)}
786 for l := range n {
787 merge.parents = append(merge.parents, (length-1)*n+l+1)
788 }
789 return h.history(append(commits, merge)...)
790}
791
792// commit is one commit history writes. Its parents are the numbers of
793// commits written before it, counted from 1, or 0 for main's tip.
794type commit struct {
795 message string
796 parents []int
797}
798
799// history writes commits onto the fixture's app main, in order, and
800// moves main to the last. Each commit is dated a second after the one
801// before it. It returns the last commit and a bundle of it.
802func (h *harness) history(commits ...commit) (tip, bundle string) {
803 t := h.t
804 t.Helper()
805 repo := h.f.Repos["app"]
806 base := git(t, repo, nil, "rev-parse", export.MainRef)
807 var b bytes.Buffer
808 for i, c := range commits {
809 who := fmt.Sprintf("Example Author <author@example.org> %d +0000", 1791190800+i)
810 fmt.Fprintf(&b, "commit refs/heads/main\nmark :%d\nauthor %s\ncommitter %s\ndata %d\n%s\n", i+1, who, who, len(c.message), c.message)
811 for j, p := range c.parents {
812 parent := base
813 if p > 0 {
814 parent = fmt.Sprintf(":%d", p)
815 }
816 if j == 0 {
817 fmt.Fprintf(&b, "from %s\n", parent)
818 } else {
819 fmt.Fprintf(&b, "merge %s\n", parent)
820 }
821 }
822 }
823 git(t, repo, b.Bytes(), "fast-import", "--quiet")
824 tip = git(t, repo, nil, "rev-parse", export.MainRef)
825 bundle = filepath.Join(t.TempDir(), "app.bundle")
826 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
827 return tip, bundle
828}
829
830// logged is the commits a page of history lists, in order.
831var logged = regexp.MustCompile(`<td class="name"><a href="/app/source/tree/([0-9a-f]+)/">`)
832
833// continued is the links a page of history has to older pages: its Older
834// link, and a link for each other line it leaves to show.
835var continued = regexp.MustCompile(`href="(/app/source/log/[0-9a-f]+\?from=[0-9a-f,]+)"`)
836
837// reach follows every link to older pages from the page at target, and
838// from each page it reaches, and counts how many of those pages show each
839// commit. It fails once it has read more than most pages.
840func (h *harness) reach(target string, most int) map[string]int {
841 h.t.Helper()
842 seen, read := map[string]int{}, map[string]bool{target: true}
843 for next := []string{target}; len(next) > 0; next = next[1:] {
844 if len(read) > most {
845 h.t.Fatalf("the links from %s reach more than %d pages", target, most)
846 }
847 page := h.page(next[0])
848 for _, m := range logged.FindAllStringSubmatch(page, -1) {
849 seen[m[1]]++
850 }
851 for _, m := range continued.FindAllStringSubmatch(page, -1) {
852 if !read[m[1]] {
853 read[m[1]] = true
854 next = append(next, m[1])
855 }
856 }
857 }
858 return seen
859}
860
861// A page of history links the older page as the commits it leaves to
862// show next, so the history of a merge whose lines run past a page is
863// shown whole: following the older links from the tip shows every commit
864// main reaches, each once. A page past the first links the newest page. A
865// ?from= that is not ascending, names a commit the page's commit does
866// not reach, or names more than MaxFrontier commits answers 404.
867func TestHistoryAcrossMerges(t *testing.T) {
868 h := newHarness(t)
869 tip, bundle := h.lines(2, 60)
870 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
871
872 at := "/app/source/log/" + tip
873 seen := map[string]int{}
874 merged := false
875 for target, pages := at, 0; target != ""; pages++ {
876 if pages > 10 {
877 t.Fatal("the older links do not end")
878 }
879 page := h.page(target)
880 for _, m := range logged.FindAllStringSubmatch(page, -1) {
881 seen[m[1]]++
882 }
883 if target != at && !strings.Contains(page, `href="`+at+`">Newest`) {
884 t.Errorf("%s does not link the newest page", target)
885 }
886 target = ""
887 if m := regexp.MustCompile(`href="(/app/source/log/[0-9a-f]+\?from=([0-9a-f,]+))">Older`).FindStringSubmatch(page); m != nil {
888 target, merged = m[1], merged || strings.Contains(m[2], ",")
889 }
890 }
891 all := strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", tip))
892 if len(seen) != len(all) {
893 t.Errorf("the older links show %d commits of the %d main reaches", len(seen), len(all))
894 }
895 for _, id := range all {
896 if seen[id] != 1 {
897 t.Errorf("the older links show %s %d times", id, seen[id])
898 }
899 }
900 if !merged {
901 t.Error("no page ends with both lines still to show")
902 }
903
904 line := strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", "--max-count=2", tip+"^2"))
905 slices.Sort(line)
906 for _, from := range []string{
907 line[1] + "," + line[0], // not ascending
908 line[0] + "," + line[0], // twice
909 tip, // not reached from the page's commit
910 strings.Repeat("1", 40), // no object
911 strings.Repeat(line[0]+",", MaxFrontier) + line[1],
912 line[0][:12],
913 "",
914 } {
915 target := "/app/source/log/" + line[1] + "?from=" + from
916 if w := h.get(target); w.Code != http.StatusNotFound {
917 t.Errorf("GET %s answered %d", target, w.Code)
918 }
919 }
920 if w := h.get(at + "?from=" + line[0] + "&from=" + line[1]); w.Code != http.StatusNotFound {
921 t.Errorf("two from parameters answered %d", w.Code)
922 }
923}
924
925// A page that leaves more than MaxFrontier commits to show starts its
926// Older link from MaxFrontier of them, links the history from each of the
927// rest, and says how many lines continue: here a merge of 65 lines, each
928// still to show once the first page ends. Following those links from the
929// tip reaches every commit main reaches.
930func TestWideHistoryStaysReachable(t *testing.T) {
931 h := newHarness(t)
932 tip, bundle := h.lines(MaxFrontier+1, 2)
933 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
934 at := "/app/source/log/" + tip
935 page := h.page(at)
936 if n := len(logged.FindAllString(page, -1)); n != LogPage {
937 t.Errorf("the page shows %d commits", n)
938 }
939 m := regexp.MustCompile(`href="` + at + `\?from=([0-9a-f,]+)">Older`).FindStringSubmatch(page)
940 if m == nil || len(strings.Split(m[1], ",")) != MaxFrontier {
941 t.Errorf("the page's Older link does not start from MaxFrontier commits: %q", m)
942 }
943 if n := len(continued.FindAllString(page, -1)); n != 2 {
944 t.Errorf("the page links %d older pages, not the Older one and one more", n)
945 }
946 if !strings.Contains(page, "Older history continues along 65 lines at once, more than the Older link follows. Each link below follows one of the remaining lines.") {
947 t.Error("the page does not say how many lines continue")
948 }
949
950 seen := h.reach(at, 20)
951 for _, id := range strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", tip)) {
952 if seen[id] == 0 {
953 t.Errorf("no link from the tip's history reaches %s", id)
954 }
955 }
956}
957
958// A page ends before a merge that would leave more than MaxLeftToShow
959// commits to show, and says so. Here the tip merges another merge and 99
960// lines, and the other merge, shown next, merges 100 lines more: 199
961// left to show. Following the links from the tip still reaches every
962// commit main reaches.
963func TestCrowdedHistoryEndsEarly(t *testing.T) {
964 h := newHarness(t)
965 var commits []commit
966 inner := commit{message: "merge 100 lines\n"}
967 outer := commit{message: "merge a merge and 99 lines\n", parents: []int{200}}
968 for l := range 199 {
969 commits = append(commits, commit{message: fmt.Sprintf("line %d\n", l), parents: []int{0}})
970 if l < 100 {
971 inner.parents = append(inner.parents, l+1)
972 } else {
973 outer.parents = append(outer.parents, l+1)
974 }
975 }
976 tip, bundle := h.history(append(commits, inner, outer)...)
977 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
978 at := "/app/source/log/" + tip
979 page := h.page(at)
980 if shown := logged.FindAllStringSubmatch(page, -1); len(shown) != 1 || shown[0][1] != tip {
981 t.Errorf("the page shows %d commits, not the tip alone", len(shown))
982 }
983 if !strings.Contains(page, "This page ends early, before a commit that would leave more lines of history than one page can link to.") {
984 t.Error("the page does not say it ends early")
985 }
986 if n := len(continued.FindAllString(page, -1)); n != 1+100-MaxFrontier {
987 t.Errorf("the page links %d older pages, not one for each of the 100 lines past MaxFrontier and the Older one", n)
988 }
989
990 seen := h.reach(at, 200)
991 for _, id := range strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", tip)) {
992 if seen[id] == 0 {
993 t.Errorf("no link from the tip's history reaches %s", id)
994 }
995 }
996}
997
998// A merge whose line of parents is longer than a record of git log keeps
999// is shown, as the first commit of a page and further down. Its subject is
1000// shown, with a note that older pages follow its first MaxParents
1001// parents. Each of those is shown or linked, and none of the others is
1002// linked.
1003func TestMergeOfManyParents(t *testing.T) {
1004 h := newHarness(t)
1005 const lines = 420
1006 var commits []commit
1007 merge := commit{message: "merge 420 lines\n"}
1008 for l := range lines {
1009 commits = append(commits, commit{message: fmt.Sprintf("line %d\n", l), parents: []int{0}})
1010 merge.parents = append(merge.parents, l+1)
1011 }
1012 commits = append(commits, merge)
1013 for i := range LogPage {
1014 commits = append(commits, commit{message: fmt.Sprintf("after the merge, commit %d\n", i), parents: []int{len(commits)}})
1015 }
1016 tip, bundle := h.history(commits...)
1017 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1018 repo := h.f.Repos["app"]
1019 w := git(t, repo, nil, "rev-parse", fmt.Sprintf("%s~%d", tip, LogPage))
1020 parents := strings.Fields(git(t, repo, nil, "log", "-1", "--format=%P", w))
1021 if len(parents) != lines || len(w)+1+len(parents)*(len(w)+1) <= maxLogRecord {
1022 t.Fatalf("the merge's ID and %d parents fit in one record of git log", len(parents))
1023 }
1024
1025 at := "/app/source/log/" + tip
1026 older := at + "?from=" + w
1027 if !strings.Contains(h.page(at), `href="`+older+`">Older`) {
1028 t.Fatal("the tip's page does not end before the merge")
1029 }
1030 note := fmt.Sprintf("merge 420 lines<p class=\"notice\">This merge has more than %d parents. Older pages follow its first %d.</p>", MaxParents, MaxParents)
1031 child := git(t, repo, nil, "rev-parse", fmt.Sprintf("%s~%d", tip, LogPage-1))
1032 // Where each page shows the merge: first on the tip page's older
1033 // page and on the merge's own history, second on its child's.
1034 for target, want := range map[string]int{older: 0, "/app/source/log/" + w: 0, "/app/source/log/" + child: 1} {
1035 page := h.page(target)
1036 shown := map[string]bool{}
1037 var order []string
1038 for _, m := range logged.FindAllStringSubmatch(page, -1) {
1039 shown[m[1]] = true
1040 order = append(order, m[1])
1041 }
1042 if len(order) != LogPage || order[want] != w {
1043 t.Errorf("GET %s does not show the merge as commit %d of %d", target, want+1, LogPage)
1044 continue
1045 }
1046 if strings.Count(page, note) != 1 {
1047 t.Errorf("GET %s does not show the merge's subject and its note once", target)
1048 }
1049 linked := map[string]bool{}
1050 for _, m := range continued.FindAllStringSubmatch(page, -1) {
1051 _, from, _ := strings.Cut(m[1], "?from=")
1052 for _, id := range strings.Split(from, ",") {
1053 linked[id] = true
1054 }
1055 }
1056 for i, id := range parents {
1057 switch {
1058 case i < MaxParents && !shown[id] && !linked[id]:
1059 t.Errorf("GET %s neither shows nor links the merge's parent %d", target, i+1)
1060 case i >= MaxParents && linked[id]:
1061 t.Errorf("GET %s links the merge's parent %d", target, i+1)
1062 }
1063 }
1064 }
1065}
1066
1067// A source request's git commands have a bound of their own, far within
1068// the request's time: a git that does not finish is stopped once it
1069// passes, and the request answers 503 and gives back its git slot. The
1070// failure is logged.
1071func TestSourceGitHasItsOwnBound(t *testing.T) {
1072 h := newHarness(t)
1073 real, err := exec.LookPath(export.GitProgram)
1074 if err != nil {
1075 t.Fatal(err)
1076 }
1077 if real, err = filepath.Abs(real); err != nil {
1078 t.Fatal(err)
1079 }
1080 slow := filepath.Join(t.TempDir(), "git")
1081 script := "#!/bin/sh\nfor a; do [ \"$a\" = ls-tree ] && exec sleep 60; done\nexec '" + real + "' \"$@\"\n"
1082 if err := os.WriteFile(slow, []byte(script), 0o755); err != nil {
1083 t.Fatal(err)
1084 }
1085 program := export.GitProgram
1086 export.GitProgram = slow
1087 t.Cleanup(func() { export.GitProgram = program })
1088 var logged []error
1089 var mu sync.Mutex
1090 h.srv.log = func(err error) { mu.Lock(); logged = append(logged, err); mu.Unlock() }
1091 h.srv.gitTime = 300 * time.Millisecond
1092
1093 start := time.Now()
1094 w := h.get("/app/source/tree/" + h.tip() + "/")
1095 if took := time.Since(start); w.Code != http.StatusServiceUnavailable || took > 5*time.Second {
1096 t.Errorf("a source request whose git does not finish answered %d after %v", w.Code, took)
1097 }
1098 if len(h.srv.slots) != 0 {
1099 t.Errorf("the request holds %d git slots once it answered", len(h.srv.slots))
1100 }
1101 mu.Lock()
1102 defer mu.Unlock()
1103 if len(logged) != 1 || !strings.Contains(logged[0].Error(), "the request held its git slot past 300ms") {
1104 t.Errorf("the server logged %v", logged)
1105 }
1106 if w := h.get("/app/knots/oc-a000002"); w.Code != http.StatusOK {
1107 t.Errorf("a knot answered %d", w.Code)
1108 }
1109}
1110
1111// A source request's bound on its git slot runs from when it takes the
1112// slot, and covers its wait for its generation's export to be read. A
1113// source request whose export is read slowly answers 503 once the bound
1114// passes, gives back its slot, and is logged, while a request for the
1115// plan, which holds no slot, waits on for the same read and is served.
1116func TestGitSlotBoundCoversTheLoad(t *testing.T) {
1117 h := newHarness(t)
1118 var mu sync.Mutex
1119 var logged []error
1120 h.srv.log = func(err error) { mu.Lock(); logged = append(logged, err); mu.Unlock() }
1121 h.srv.gitTime = 300 * time.Millisecond
1122 hold := make(chan struct{})
1123 h.srv.loading = func(export.Generation) { <-hold }
1124
1125 plan := make(chan *httptest.ResponseRecorder, 1)
1126 go func() {
1127 w := httptest.NewRecorder()
1128 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
1129 plan <- w
1130 }()
1131 eventually(t, "the plan waits for the export to be read", func() bool { return len(h.srv.loaders) == 1 })
1132 start := time.Now()
1133 w := h.get("/app/source/tree/" + h.tip() + "/")
1134 if took := time.Since(start); w.Code != http.StatusServiceUnavailable || took > 5*time.Second {
1135 t.Errorf("a source request whose export is read slowly answered %d after %v", w.Code, took)
1136 }
1137 if len(h.srv.slots) != 0 {
1138 t.Errorf("the request holds %d git slots once it answered", len(h.srv.slots))
1139 }
1140 mu.Lock()
1141 if len(logged) != 1 || !strings.Contains(logged[0].Error(), "the request held its git slot past 300ms") ||
1142 !strings.Contains(logged[0].Error(), "export to be read") {
1143 t.Errorf("the server logged %v", logged)
1144 }
1145 mu.Unlock()
1146
1147 close(hold)
1148 select {
1149 case w := <-plan:
1150 if w.Code != http.StatusOK {
1151 t.Errorf("the plan answered %d once its export was read", w.Code)
1152 }
1153 case <-time.After(10 * time.Second):
1154 t.Fatal("the plan was not served once its export was read")
1155 }
1156 h.page("/app/source/tree/" + h.tip() + "/")
1157}
1158
1159// A source request gives back its git slot before it renders its page, so
1160// a page that renders slowly holds no slot, and is not held to the bound
1161// on holding one. While one renders, past that bound, another source
1162// request is served, and the first is served in full once it renders.
1163func TestRenderingHoldsNoGitSlot(t *testing.T) {
1164 h := newHarness(t)
1165 h.page("/")
1166 h.srv.gitTime = 300 * time.Millisecond
1167 rendering, hold := make(chan struct{}), make(chan struct{})
1168 var first atomic.Bool
1169 h.srv.rendering = func(name string) {
1170 if name == "tree" && first.CompareAndSwap(false, true) {
1171 close(rendering)
1172 <-hold
1173 }
1174 }
1175
1176 served := make(chan *httptest.ResponseRecorder, 1)
1177 go func() {
1178 w := httptest.NewRecorder()
1179 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/source/tree/"+h.tip()+"/", nil))
1180 served <- w
1181 }()
1182 select {
1183 case <-rendering:
1184 case <-time.After(10 * time.Second):
1185 t.Fatal("the source request did not render")
1186 }
1187 if len(h.srv.slots) != 0 {
1188 t.Errorf("a source request holds %d git slots while it renders", len(h.srv.slots))
1189 }
1190 h.page("/app/source/blob/" + h.tip() + "/docs/guide.md")
1191 time.Sleep(2 * h.srv.gitTime)
1192 close(hold)
1193 select {
1194 case w := <-served:
1195 if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "guide.md") {
1196 t.Errorf("a source request that rendered past the bound on its slot answered %d", w.Code)
1197 }
1198 case <-time.After(10 * time.Second):
1199 t.Fatal("the source request was not served once it rendered")
1200 }
1201}
1202
1203// A SHA-256 project's commits are served by their 64 hex digits alone.
1204// The first 40 of them, which git would read as an abbreviation, answer
1205// 404 on every source route, so each page has one address.
1206func TestSHA256CommitIDs(t *testing.T) {
1207 h := newHarness(t)
1208 repo := filepath.Join(t.TempDir(), "app.git")
1209 git(t, repo, nil, "init", "--quiet", "--bare", "--template=", "--initial-branch=main", "--object-format=sha256")
1210 readme := "# app\n\nA SHA-256 repository.\n"
1211 who := "Example Author <author@example.org> 1791190800 +0000"
1212 stream := fmt.Sprintf("commit refs/heads/main\nauthor %s\ncommitter %s\ndata 7\nsha256\n\nM 100644 inline README.md\ndata %d\n%s\n",
1213 who, who, len(readme), readme)
1214 git(t, repo, []byte(stream), "fast-import", "--quiet")
1215 tip := git(t, repo, nil, "rev-parse", export.MainRef)
1216 if len(tip) != 64 {
1217 t.Fatalf("the tip is %q", tip)
1218 }
1219 bundle := filepath.Join(t.TempDir(), "app.bundle")
1220 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
1221 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1222
1223 for _, route := range []string{"/app/source/tree/%s/", "/app/source/blob/%s/README.md", "/app/source/log/%s"} {
1224 if page := h.page(fmt.Sprintf(route, tip)); !strings.Contains(page, tip[:12]) {
1225 t.Errorf("%s does not name the commit", fmt.Sprintf(route, tip))
1226 }
1227 if w := h.get(fmt.Sprintf(route, tip[:40])); w.Code != http.StatusNotFound {
1228 t.Errorf("%s answered %d", fmt.Sprintf(route, tip[:40]), w.Code)
1229 }
1230 }
1231 if w := h.get("/app/source/"); w.Header().Get("Location") != "/app/source/tree/"+tip+"/" {
1232 t.Errorf("/app/source/ redirects to %q", w.Header().Get("Location"))
1233 }
1234}
1235
1236// A file of exactly MaxFile bytes of newlines is shown to MaxLines lines,
1237// and its page says where it stops. A README longer than a page shows is
1238// shown in part.
1239func TestLongFileIsShownInPart(t *testing.T) {
1240 h := newHarness(t)
1241 tip, bundle := h.commitMain("app: long files\n",
1242 file{"100644", "newlines.txt", strings.Repeat("\n", MaxFile)},
1243 file{"100644", "long/README.md", strings.Repeat("a line of the README\n", 2*MaxLines)},
1244 file{"100644", "wide.txt", strings.Repeat("<", MaxFile)},
1245 )
1246 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1247
1248 page := h.page("/app/source/blob/" + tip + "/newlines.txt")
1249 last := fmt.Sprintf(`id="L%d"`, MaxLines)
1250 if !strings.Contains(page, last) || strings.Contains(page, fmt.Sprintf(`id="L%d"`, MaxLines+1)) {
1251 t.Errorf("the file of newlines is not shown to line %d", MaxLines)
1252 }
1253 if want := fmt.Sprintf("The page stops at line %d of %d.", MaxLines, MaxFile); !strings.Contains(page, want) {
1254 t.Errorf("the page does not say %q", want)
1255 }
1256 if len(page) > MaxShown {
1257 t.Errorf("the page of a file of newlines is %d bytes, past MaxShown", len(page))
1258 }
1259
1260 // One line of MaxFile characters that each escape to four bytes is
1261 // cut where MaxShown is reached.
1262 page = h.page("/app/source/blob/" + tip + "/wide.txt")
1263 if !strings.Contains(page, "The page stops at line 1 of 1.") || len(page) > MaxShown+64<<10 {
1264 t.Errorf("the page of one wide line is %d bytes", len(page))
1265 }
1266
1267 page = h.page("/app/source/tree/" + tip + "/long/")
1268 if !strings.Contains(page, "This README is longer than a page shows, and only its start is shown.") {
1269 t.Error("the long README is not marked as shown in part")
1270 }
1271 if n := strings.Count(page, "a line of the README"); n != MaxLines {
1272 t.Errorf("the long README shows %d lines, not %d", n, MaxLines)
1273 }
1274}
1275
1276// A chain of knots as deep as the graph's knot limit allows renders its
1277// milestone to MaxPlanDepth levels, counts every knot under it, and
1278// names MaxPlanDepth parents in the deepest knot's trail. The plan page's
1279// structure is built once for the generation. Siblings that block one
1280// another in a cycle share the last stage of their path.
1281func TestDeepPlan(t *testing.T) {
1282 h := newHarness(t)
1283 var chain []string
1284 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
1285 p := &e.Projects[0]
1286 for i := range knot.MaxKnots - len(p.Knots) - 3 {
1287 id := fmt.Sprintf("oc-c%06x", i)
1288 k := export.Knot{ID: id, Type: "outcome", Status: "open", Active: true, State: "ready",
1289 Title: fmt.Sprintf("Level %d of the chain", i), Created: "2026-10-01", CreatedBy: "operator"}
1290 if i == 0 {
1291 p.Roots = append(p.Roots, id)
1292 } else {
1293 k.Parent = chain[i-1]
1294 p.Knots[len(p.Knots)-1].Children = []string{id}
1295 }
1296 chain = append(chain, id)
1297 p.Knots = append(p.Knots, k)
1298 }
1299 // Under the first link, a path whose two last siblings wait on
1300 // each other.
1301 free, a, b := "oc-d000001", "oc-d000002", "oc-d000003"
1302 for _, k := range []export.Knot{
1303 {ID: free, BlockedBy: []string{}},
1304 {ID: a, BlockedBy: []string{free, b}},
1305 {ID: b, BlockedBy: []string{a}},
1306 } {
1307 k.Type, k.Status, k.State, k.Title, k.Parent = "outcome", "open", "blocked", "Sibling "+k.ID, chain[0]
1308 p.Knots = append(p.Knots, k)
1309 }
1310 for i := range p.Knots {
1311 if p.Knots[i].ID == chain[0] {
1312 p.Knots[i].Children = append(p.Knots[i].Children, free, a, b)
1313 }
1314 }
1315 })
1316
1317 page := h.page("/")
1318 if want := fmt.Sprintf("%d of %d done", 0, len(chain)-1+3); !strings.Contains(page, want) {
1319 t.Errorf("the chain's milestone does not count every knot under it as %q", want)
1320 }
1321 if !strings.Contains(page, `href="/app/knots/`+chain[MaxPlanDepth]+`"`) || strings.Contains(page, `href="/app/knots/`+chain[MaxPlanDepth+1]+`"`) {
1322 t.Errorf("the chain's tree is not shown to %d levels", MaxPlanDepth)
1323 }
1324 if n := strings.Count(page, ">more on its page<"); n != 1 {
1325 t.Errorf("%d rows say there is more on their page; the chain's deepest shown row does", n)
1326 }
1327 if len(page) > 256<<10 {
1328 t.Errorf("the plan page is %d bytes", len(page))
1329 }
1330 paths := section(t, page, `id="paths-h"`, `id="ms-h"`)
1331 stage := regexp.MustCompile(`<span class="stage-num">(\d+)</span><ul class="plain">(.*?)</ul>`)
1332 var stages []string
1333 for _, m := range stage.FindAllStringSubmatch(paths, -1) {
1334 if strings.Contains(m[2], "Sibling") {
1335 var ids []string
1336 for _, id := range regexp.MustCompile(`"mono muted">(oc-d00000\d)<`).FindAllStringSubmatch(m[2], -1) {
1337 ids = append(ids, id[1])
1338 }
1339 stages = append(stages, m[1]+":"+strings.Join(ids, ","))
1340 }
1341 }
1342 if got := strings.Join(stages, " "); got != "1:oc-d000001 2:oc-d000002,oc-d000003" {
1343 t.Errorf("the siblings' path has stages %q", got)
1344 }
1345
1346 h.srv.mu.Lock()
1347 plan := h.srv.cached.idx.plan
1348 h.srv.mu.Unlock()
1349 h.page("/")
1350 h.srv.mu.Lock()
1351 again := h.srv.cached.idx.plan
1352 h.srv.mu.Unlock()
1353 if plan != again {
1354 t.Error("the plan page's structure was built again for the same generation")
1355 }
1356
1357 deepest := chain[len(chain)-1]
1358 page = h.page("/app/knots/" + deepest)
1359 trail := section(t, page, `<nav class="trail"`, `</nav>`)
1360 if n := strings.Count(trail, `<a href="/app/knots/`); n != MaxPlanDepth || !strings.Contains(trail, "<span>…</span>") {
1361 t.Errorf("the deepest knot's trail names %d parents, or does not mark those above them", n)
1362 }
1363 if !strings.Contains(trail, chain[len(chain)-2]) || strings.Contains(trail, `"/app/knots/`+chain[len(chain)-2-MaxPlanDepth]+`"`) {
1364 t.Error("the trail does not name the nearest parents alone")
1365 }
1366}
1367
1368// Every response carries the strict policy, and the policy admits the
1369// page's one inline stylesheet and one inline script by their hashes and
1370// nothing from another origin.
1371func TestEveryResponseCarriesTheCSP(t *testing.T) {
1372 h := newHarness(t)
1373 for _, c := range []struct{ method, target string }{
1374 {"GET", "/"},
1375 {"GET", "/app/knots/oc-a000002"},
1376 {"GET", "/app/source/"},
1377 {"GET", "/app/source/tree/" + h.tip() + "/"},
1378 {"GET", "/app/source/blob/" + h.tip() + "/README.md"},
1379 {"GET", "/no/such/page"},
1380 {"POST", "/"},
1381 {"HEAD", "/"},
1382 } {
1383 w := h.do(c.method, c.target)
1384 got := w.Header().Get("Content-Security-Policy")
1385 if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" {
1386 t.Errorf("%s %s answered with policy %q", c.method, c.target, got)
1387 }
1388 }
1389 for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} {
1390 if !strings.Contains(csp, directive) {
1391 t.Errorf("the policy lacks %s", directive)
1392 }
1393 }
1394 for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} {
1395 if strings.Contains(csp, loose) {
1396 t.Errorf("the policy holds %q", loose)
1397 }
1398 }
1399
1400 page := h.page("/")
1401 inline := func(tag string) string {
1402 t.Helper()
1403 m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1)
1404 if len(m) != 1 || strings.Count(page, "<"+tag) != 1 {
1405 t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag)
1406 }
1407 sum := sha256.Sum256([]byte(m[0][1]))
1408 return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
1409 }
1410 if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") {
1411 t.Errorf("the policy does not admit the page's script, %s", hash)
1412 }
1413 if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") {
1414 t.Errorf("the policy does not admit the page's stylesheet, %s", hash)
1415 }
1416 for _, external := range []string{"<link", " src=", "@import", "url("} {
1417 if strings.Contains(page, external) {
1418 t.Errorf("the plan page holds %q", external)
1419 }
1420 }
1421}
1422
1423// A request serves everything from the generation it opened, though
1424// another activates while it runs, and that generation outlives the
1425// activation until the request releases it.
1426func TestARequestKeepsItsGeneration(t *testing.T) {
1427 h := newHarness(t)
1428 paused, resume := make(chan export.Generation), make(chan struct{})
1429 var once sync.Once
1430 h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) }
1431 served := make(chan *httptest.ResponseRecorder)
1432 go func() {
1433 w := httptest.NewRecorder()
1434 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/knots/oc-a000001", nil))
1435 served <- w
1436 }()
1437 old := <-paused
1438
1439 next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1440 if next.Sequence == old.Sequence {
1441 t.Fatal("the publish did not activate a new generation")
1442 }
1443 if _, err := os.Stat(old.Dir); err != nil {
1444 t.Fatalf("the generation a request holds was deleted: %v", err)
1445 }
1446 close(resume)
1447 w := <-served
1448 if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app&#39;s plan") || strings.Contains(body, "second plan") {
1449 t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body)
1450 }
1451 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the second plan") {
1452 t.Error("the next request does not serve the new generation")
1453 }
1454
1455 // Released, the old generation goes with the next activation.
1456 h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1457 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1458 t.Errorf("the released generation is still on disk: %v", err)
1459 }
1460}
1461
1462// eventually waits up to ten seconds for cond to hold.
1463func eventually(t *testing.T, what string, cond func() bool) {
1464 t.Helper()
1465 for deadline := time.Now().Add(10 * time.Second); !cond(); time.Sleep(time.Millisecond) {
1466 if time.Now().After(deadline) {
1467 t.Fatalf("timed out waiting until %s", what)
1468 }
1469 }
1470}
1471
1472// renamed changes the title of the fixture's first knot.
1473func renamed(title string) func(*export.Export) {
1474 return func(e *export.Export) { e.Projects[0].Knots[0].Title = title }
1475}
1476
1477// Requests that wait for a generation together read its export once.
1478// While it is read, a newer generation is read on its own, and at most
1479// MaxLoads exports are read at once. A request whose load ends after a
1480// newer generation was activated waits for that one, so every request is
1481// served the generation active when its snapshot is ready, and an older
1482// read that finishes last does not displace the newest snapshot.
1483func TestExportLoadsCoalesce(t *testing.T) {
1484 h := newHarness(t)
1485 var mu sync.Mutex
1486 loads := map[int64]int{}
1487 holds := map[int64]chan struct{}{}
1488 hold := func(g export.Generation) chan struct{} {
1489 mu.Lock()
1490 defer mu.Unlock()
1491 if holds[g.Sequence] == nil {
1492 holds[g.Sequence] = make(chan struct{})
1493 }
1494 return holds[g.Sequence]
1495 }
1496 h.srv.loading = func(g export.Generation) {
1497 mu.Lock()
1498 loads[g.Sequence]++
1499 mu.Unlock()
1500 <-hold(g)
1501 }
1502 loaded := func(g export.Generation) int {
1503 mu.Lock()
1504 defer mu.Unlock()
1505 return loads[g.Sequence]
1506 }
1507 var opens atomic.Int32
1508 h.srv.opened = func(export.Generation) { opens.Add(1) }
1509 get := func(n int) chan *httptest.ResponseRecorder {
1510 served := make(chan *httptest.ResponseRecorder, n)
1511 for range n {
1512 go func() {
1513 w := httptest.NewRecorder()
1514 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/knots/oc-a000001", nil))
1515 served <- w
1516 }()
1517 }
1518 return served
1519 }
1520 expect := func(served chan *httptest.ResponseRecorder, n int, title string) {
1521 t.Helper()
1522 for range n {
1523 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
1524 t.Errorf("a request answered %d, not with %q", w.Code, title)
1525 }
1526 }
1527 }
1528 waiting := func(n int) func() bool { return func() bool { return len(h.srv.loadWaiting) == n } }
1529
1530 first := h.active()
1531 firstServed := get(10)
1532 eventually(t, "ten requests wait for the first generation's read", func() bool {
1533 return loaded(first) == 1 && len(h.srv.loadWaiting) == 10
1534 })
1535 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1536 secondServed := get(1)
1537 eventually(t, "the second generation is read", func() bool { return loaded(second) == 1 })
1538
1539 // Both loaders are taken, so the third generation waits for one.
1540 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1541 thirdServed := get(1)
1542 eventually(t, "a request waits for the third generation", waiting(12))
1543 time.Sleep(20 * time.Millisecond)
1544 if n := loaded(third); n != 0 {
1545 t.Errorf("a third export was read while %d were", MaxLoads)
1546 }
1547 if n := opens.Load(); n != 0 {
1548 t.Errorf("%d requests opened a generation while they waited for its read", n)
1549 }
1550
1551 // The second read ends, and its request finds the third generation
1552 // active, and waits for that read with the third's request.
1553 close(hold(second))
1554 eventually(t, "the third generation is read", func() bool { return loaded(third) == 1 })
1555 close(hold(third))
1556 expect(secondServed, 1, "Readers browse the third plan")
1557 expect(thirdServed, 1, "Readers browse the third plan")
1558 close(hold(first))
1559 expect(firstServed, 10, "Readers browse the third plan")
1560
1561 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the third plan") {
1562 t.Error("the first generation's read displaced the third's")
1563 }
1564 for _, g := range []export.Generation{first, second, third} {
1565 if n := loaded(g); n != 1 {
1566 t.Errorf("generation %d's export was read %d times", g.Sequence, n)
1567 }
1568 }
1569}
1570
1571// Source requests past MaxGit wait, MaxWaiting of them, and one more
1572// answers 503 at once. A waiting request holds no generation, so an
1573// activation while the server is saturated deletes the old generation,
1574// and every waiting request serves the new one. A request's time runs
1575// from its arrival, so one that waits past it answers 503.
1576func TestSourceAdmission(t *testing.T) {
1577 h := newHarness(t)
1578 // The requests that hold the slots wait for the test, not for git, so
1579 // the bound on holding a slot is no part of this test.
1580 h.srv.gitTime = time.Hour
1581 var admitted atomic.Int32
1582 release := make(chan struct{})
1583 h.srv.admitted = func() {
1584 admitted.Add(1)
1585 <-release
1586 }
1587 target := "/app/source/tree/" + h.tip() + "/"
1588 get := func(n int) chan *httptest.ResponseRecorder {
1589 served := make(chan *httptest.ResponseRecorder, n)
1590 for range n {
1591 go func() {
1592 w := httptest.NewRecorder()
1593 h.srv.ServeHTTP(w, httptest.NewRequest("GET", target, nil))
1594 served <- w
1595 }()
1596 }
1597 return served
1598 }
1599
1600 old := h.active()
1601 served := get(MaxGit + MaxWaiting)
1602 eventually(t, "every slot is taken and MaxWaiting requests wait", func() bool {
1603 return admitted.Load() == MaxGit && len(h.srv.waiting) == MaxWaiting
1604 })
1605 if w := h.get(target); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1606 t.Errorf("a source request past MaxWaiting answered %d, Retry-After %q", w.Code, w.Header().Get("Retry-After"))
1607 }
1608 h.page("/") // a page that runs no git is served still
1609
1610 tip, bundle := h.commitMain("app: a commit while the server is saturated\n", file{"100644", "saturated.txt", "saturated\n"})
1611 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1612 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1613 t.Errorf("a generation no request had opened outlived the activation: %v", err)
1614 }
1615 close(release)
1616 for range MaxGit + MaxWaiting {
1617 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "/app/source/tree/"+tip+"/") {
1618 t.Errorf("a waiting request answered %d, not from the new generation", w.Code)
1619 }
1620 }
1621
1622 // A request that waits past its time answers 503. Those that held
1623 // the slots meanwhile ran out of time too.
1624 h.srv.timeout = 200 * time.Millisecond
1625 h.srv.log = func(error) {}
1626 admitted.Store(0)
1627 release = make(chan struct{})
1628 held := get(MaxGit)
1629 eventually(t, "every slot is taken", func() bool { return admitted.Load() == MaxGit })
1630 start := time.Now()
1631 if w := h.get(target); w.Code != http.StatusServiceUnavailable {
1632 t.Errorf("a request that waited past its time answered %d", w.Code)
1633 }
1634 if waited := time.Since(start); waited > 5*time.Second {
1635 t.Errorf("a request waited %v past its time of 200ms", waited)
1636 }
1637 close(release)
1638 for range MaxGit {
1639 if w := <-held; w.Code != http.StatusServiceUnavailable {
1640 t.Errorf("a request that ran out of time answered %d", w.Code)
1641 }
1642 }
1643}
1644
1645// stallingListener accepts connections whose writes stall until release
1646// is closed, while stall is set. Each sends on stalled the first time one
1647// of its writes stalls.
1648type stallingListener struct {
1649 net.Listener
1650 stall atomic.Bool
1651 release chan struct{}
1652 stalled chan struct{}
1653}
1654
1655func (l *stallingListener) Accept() (net.Conn, error) {
1656 c, err := l.Listener.Accept()
1657 if err != nil || !l.stall.Load() {
1658 return c, err
1659 }
1660 return &stallingConn{Conn: c, l: l}, nil
1661}
1662
1663type stallingConn struct {
1664 net.Conn
1665 l *stallingListener
1666 once sync.Once
1667}
1668
1669func (c *stallingConn) Write(p []byte) (int, error) {
1670 c.once.Do(func() { c.l.stalled <- struct{}{} })
1671 <-c.l.release
1672 return c.Conn.Write(p)
1673}
1674
1675// Readers that never read their responses hold no git slot and no
1676// generation: more of them than MaxGit and MaxWaiting together are
1677// stalled writing, and a new reader is still served, and an activation
1678// deletes the generation they were served from.
1679func TestSlowReadersHoldNothing(t *testing.T) {
1680 h := newHarness(t)
1681 ln, err := net.Listen("tcp", "127.0.0.1:0")
1682 if err != nil {
1683 t.Fatal(err)
1684 }
1685 n := MaxGit + MaxWaiting + 4
1686 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
1687 sl.stall.Store(true)
1688 srv := &http.Server{Handler: h.srv}
1689 go srv.Serve(sl)
1690 var conns []net.Conn
1691 defer func() {
1692 close(sl.release)
1693 for _, c := range conns {
1694 c.Close()
1695 }
1696 srv.Close()
1697 }()
1698
1699 old := h.active()
1700 target := "/app/source/blob/" + h.tip() + "/docs/guide.md"
1701 for range n {
1702 c, err := net.Dial("tcp", ln.Addr().String())
1703 if err != nil {
1704 t.Fatal(err)
1705 }
1706 conns = append(conns, c)
1707 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
1708 }
1709 for i := range n {
1710 select {
1711 case <-sl.stalled:
1712 case <-time.After(10 * time.Second):
1713 t.Fatalf("%d of %d slow readers' responses were written; the rest wait", i, n)
1714 }
1715 }
1716 sl.stall.Store(false)
1717 if len(h.srv.slots) != 0 || len(h.srv.waiting) != 0 {
1718 t.Errorf("slow readers hold %d git slots, and %d requests wait", len(h.srv.slots), len(h.srv.waiting))
1719 }
1720
1721 client := &http.Client{Timeout: 10 * time.Second}
1722 resp, err := client.Get("http://" + ln.Addr().String() + target)
1723 if err != nil {
1724 t.Fatal(err)
1725 }
1726 resp.Body.Close()
1727 if resp.StatusCode != http.StatusOK {
1728 t.Errorf("a new reader answered %d while slow readers stall", resp.StatusCode)
1729 }
1730 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(*export.Export) {})
1731 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1732 t.Errorf("the generation slow readers were served from outlived the activation: %v", err)
1733 }
1734}
1735
1736// Before the first activation the server says nothing is published, and
1737// it answers GET and HEAD alone.
1738func TestNothingPublishedAndMethods(t *testing.T) {
1739 store, err := export.OpenStore(t.TempDir(), nil)
1740 if err != nil {
1741 t.Fatal(err)
1742 }
1743 srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }})
1744 w := httptest.NewRecorder()
1745 srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
1746 if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") {
1747 t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body)
1748 }
1749
1750 h := newHarness(t)
1751 for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} {
1752 w := h.do(method, "/")
1753 if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" {
1754 t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow"))
1755 }
1756 }
1757}
1758
1759// tooLarge checks that GET target answers with the one short page that
1760// says a page is too large.
1761func (h *harness) tooLarge(target string) {
1762 h.t.Helper()
1763 w := h.get(target)
1764 if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) {
1765 h.t.Errorf("GET %s answered %d with %d bytes, not the page that says it is too large", target, w.Code, w.Body.Len())
1766 }
1767 if n, _ := h.srv.holding(); n != 0 {
1768 h.t.Errorf("GET %s kept %d pieces of the budget", target, n)
1769 }
1770}
1771
1772// A response's body is at most MaxResponse bytes. A page that would pass
1773// the bound answers with the one short page that says it is too large,
1774// and the failure is logged: a knot whose body passes MaxResponse, and,
1775// under a smaller bound, a file, a directory, a page of history and the
1776// plan page. A page within the bound is served on each route.
1777func TestPageTooLarge(t *testing.T) {
1778 h := newHarness(t)
1779 var logged []string
1780 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
1781 files := []file{{"100644", "wide.txt", strings.Repeat("<", 16<<10)}}
1782 for i := range 32 {
1783 files = append(files, file{"100644", fmt.Sprintf("wide/%02d-%s", i, strings.Repeat("n", 1000)), "x\n"})
1784 }
1785 h.commitMain("app: a wide file and a wide directory\n", files...)
1786 var tip, bundle string
1787 for i := range 8 {
1788 tip, bundle = h.commitMain(fmt.Sprintf("%d %s\n", i, strings.Repeat(`"`, maxLogText)))
1789 }
1790 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
1791 p := &e.Projects[0]
1792 p.SourceTip = tip
1793 p.Knots[0].Body = strings.Repeat("a", MaxResponse)
1794 for i := range 100 {
1795 p.Knots = append(p.Knots, export.Knot{ID: fmt.Sprintf("oc-e%06x", i), Type: "outcome", Status: "open",
1796 Active: true, State: "ready", Title: strings.Repeat(`"`, knot.MaxTitle), Created: "2026-10-01", CreatedBy: "operator"})
1797 }
1798 })
1799
1800 h.tooLarge("/app/knots/" + h.f.Export.Projects[0].Knots[0].ID)
1801 h.page("/app/knots/oc-a000002")
1802
1803 h.srv.maxResponse = 32 << 10
1804 at := "/app/source/blob/" + tip + "/"
1805 h.tooLarge(at + "wide.txt")
1806 h.page(at + "docs/guide.md")
1807 at = "/app/source/tree/" + tip + "/"
1808 h.tooLarge(at + "wide/")
1809 h.page(at + "docs/")
1810 h.tooLarge("/app/source/log/" + tip)
1811 h.page("/app/source/log/" + git(t, h.f.Repos["app"], nil, "rev-parse", tip+"~8"))
1812 h.tooLarge("/")
1813
1814 if len(logged) != 5 {
1815 t.Errorf("%d failures were logged for 5 pages too large: %q", len(logged), logged)
1816 }
1817 for _, l := range logged {
1818 if !strings.Contains(l, "larger than") {
1819 t.Errorf("the server logged %q", l)
1820 }
1821 }
1822 if len(tooLargePage) > 16<<10 {
1823 t.Errorf("the page that says a page is too large is %d bytes", len(tooLargePage))
1824 }
1825}
1826
1827// holding is how many pieces of the budget responses hold, and how many
1828// of those the large budget counts.
1829func (s *Server) holding() (held, large int) {
1830 s.pieces.Lock()
1831 defer s.pieces.Unlock()
1832 return s.held, s.large
1833}
1834
1835// Rendered responses share a budget of MaxBuffered bytes, which each
1836// holds from when it starts rendering until it is written. Responses
1837// larger than SmallPage hold at most MaxLarge of it between them, their
1838// first SmallPage bytes counted. Readers that never read large pages ask
1839// for more than the whole budget, in pages of three sizes: one piece past
1840// SmallPage, 1 MiB, and 4 MiB. Without the first SmallPage bytes counted,
1841// 64 readers of the 1 MiB page would hold all of the budget. Once the
1842// readers' pages hold what fits in MaxLarge, a large page answers 503 at
1843// once, while small pages still render: the plan, a knot and a
1844// directory. The server's heap grows by no more than the budget, and the
1845// budget is whole again once the readers read.
1846func TestSlowReadersShareTheBudget(t *testing.T) {
1847 for _, pieces := range []int{smallPieces + 1, 16, 64} {
1848 t.Run(fmt.Sprintf("%d pieces", pieces), func(t *testing.T) { slowReadersOfPages(t, pieces) })
1849 }
1850}
1851
1852// slowReadersOfPages runs TestSlowReadersShareTheBudget with large pages
1853// of the number of pieces given.
1854func slowReadersOfPages(t *testing.T, pieces int) {
1855 h := newHarness(t)
1856 target := "/app/knots/" + h.f.Export.Projects[0].Knots[0].ID
1857 body := func(at time.Duration, text string) {
1858 h.publish(exporttest.SignedAt.Add(at), nil, func(e *export.Export) { e.Projects[0].Knots[0].Body = text })
1859 }
1860 body(time.Minute, "x")
1861 rest := len(h.page(target)) - 1
1862 body(2*time.Minute, strings.Repeat("a line of a long body\n", (pieces*pieceSize-rest-1024)/22))
1863 size := len(h.page(target))
1864 if got := (size + pieceSize - 1) / pieceSize; got != pieces {
1865 t.Fatalf("the large page takes %d pieces, not %d", got, pieces)
1866 }
1867 fit := largePieces / pieces
1868 n := MaxBuffered/size + 2
1869
1870 ln, err := net.Listen("tcp", "127.0.0.1:0")
1871 if err != nil {
1872 t.Fatal(err)
1873 }
1874 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
1875 sl.stall.Store(true)
1876 srv := &http.Server{Handler: h.srv}
1877 go srv.Serve(sl)
1878 var conns []net.Conn
1879 released := false
1880 defer func() {
1881 if !released {
1882 close(sl.release)
1883 }
1884 for _, c := range conns {
1885 c.Close()
1886 }
1887 srv.Close()
1888 }()
1889
1890 var before runtime.MemStats
1891 runtime.GC()
1892 runtime.ReadMemStats(&before)
1893 // One reader at a time, each stalled before the next asks, so the
1894 // readers that fill the budget are the first fit of them.
1895 for i := range n {
1896 c, err := net.Dial("tcp", ln.Addr().String())
1897 if err != nil {
1898 t.Fatal(err)
1899 }
1900 conns = append(conns, c)
1901 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
1902 select {
1903 case <-sl.stalled:
1904 case <-time.After(10 * time.Second):
1905 t.Fatalf("reader %d of %d was not answered", i+1, n)
1906 }
1907 }
1908 sl.stall.Store(false)
1909 var after runtime.MemStats
1910 runtime.GC()
1911 runtime.ReadMemStats(&after)
1912 if held, large := h.srv.holding(); held != fit*pieces || large != fit*pieces {
1913 t.Errorf("slow readers hold %d pieces, %d of them counted as large; %d pages of %d pieces fit", held, large, fit, pieces)
1914 }
1915 if grew := int64(after.HeapAlloc) - int64(before.HeapAlloc); grew > MaxBuffered+8<<20 {
1916 t.Errorf("%d slow readers of %d bytes each grew the heap by %d bytes, past MaxBuffered", n, size, grew)
1917 }
1918
1919 client := &http.Client{Timeout: 10 * time.Second}
1920 get := func(target string) (int, string) {
1921 t.Helper()
1922 resp, err := client.Get("http://" + ln.Addr().String() + target)
1923 if err != nil {
1924 t.Fatal(err)
1925 }
1926 defer resp.Body.Close()
1927 io.Copy(io.Discard, resp.Body)
1928 return resp.StatusCode, resp.Header.Get("Retry-After")
1929 }
1930 if code, retry := get(target); code != http.StatusServiceUnavailable || retry == "" {
1931 t.Errorf("a page the budget has no room for answered %d, Retry-After %q", code, retry)
1932 }
1933 for _, small := range []string{"/", "/app/knots/oc-a000002", "/app/source/tree/" + h.tip() + "/"} {
1934 if code, _ := get(small); code != http.StatusOK {
1935 t.Errorf("the small page %s answered %d while slow readers hold MaxLarge", small, code)
1936 }
1937 }
1938
1939 close(sl.release)
1940 released = true
1941 codes := map[int]int{}
1942 for _, c := range conns {
1943 c.SetReadDeadline(time.Now().Add(10 * time.Second))
1944 resp, err := http.ReadResponse(bufio.NewReader(c), nil)
1945 if err != nil {
1946 t.Fatal(err)
1947 }
1948 read, err := io.Copy(io.Discard, resp.Body)
1949 resp.Body.Close()
1950 if err != nil || resp.StatusCode == http.StatusOK && read != int64(size) {
1951 t.Errorf("a slow reader read %d bytes of %d: %v", read, size, err)
1952 }
1953 codes[resp.StatusCode]++
1954 }
1955 if codes[http.StatusOK] != fit || codes[http.StatusServiceUnavailable] != n-fit {
1956 t.Errorf("of %d slow readers, %d were served and %d answered 503; %d pages fit the budget",
1957 n, codes[http.StatusOK], codes[http.StatusServiceUnavailable], fit)
1958 }
1959 eventually(t, "the budget is whole again", func() bool { held, _ := h.srv.holding(); return held == 0 })
1960}
1961
1962// A load starts only once a request that waits for it takes a loader
1963// slot. While MaxLoads loads run, a request for a newer generation waits
1964// for a slot, holding no generation, until its time runs out, whatever
1965// its route, or its reader goes away. Neither leaves a load behind.
1966func TestExportLoadWaitsEnd(t *testing.T) {
1967 h := newHarness(t)
1968 var mu sync.Mutex
1969 var logged []string
1970 h.srv.log = func(err error) {
1971 mu.Lock()
1972 defer mu.Unlock()
1973 logged = append(logged, err.Error())
1974 }
1975 loads := map[int64]int{}
1976 hold := make(chan struct{})
1977 h.srv.loading = func(g export.Generation) {
1978 mu.Lock()
1979 loads[g.Sequence]++
1980 mu.Unlock()
1981 <-hold
1982 }
1983 loaded := func(g export.Generation) int {
1984 mu.Lock()
1985 defer mu.Unlock()
1986 return loads[g.Sequence]
1987 }
1988 serve := func(r *http.Request) chan *httptest.ResponseRecorder {
1989 served := make(chan *httptest.ResponseRecorder, 1)
1990 go func() {
1991 w := httptest.NewRecorder()
1992 h.srv.ServeHTTP(w, r)
1993 served <- w
1994 }()
1995 return served
1996 }
1997 expect := func(served chan *httptest.ResponseRecorder, title string) {
1998 t.Helper()
1999 select {
2000 case w := <-served:
2001 if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
2002 t.Errorf("a request answered %d, not with %q", w.Code, title)
2003 }
2004 case <-time.After(10 * time.Second):
2005 t.Fatalf("a request was not answered with %q", title)
2006 }
2007 }
2008
2009 first := h.active()
2010 firstServed := serve(httptest.NewRequest("GET", "/", nil))
2011 eventually(t, "the first generation is read", func() bool { return loaded(first) == 1 })
2012 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
2013 secondServed := serve(httptest.NewRequest("GET", "/", nil))
2014 eventually(t, "both loader slots are taken", func() bool { return loaded(second) == 1 })
2015
2016 // A request that runs no git runs out of time waiting, and answers
2017 // 503.
2018 h.srv.timeout = 200 * time.Millisecond
2019 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
2020 select {
2021 case w := <-serve(httptest.NewRequest("GET", "/app/knots/oc-a000001", nil)):
2022 if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
2023 t.Errorf("a request that waited past its time for a read answered %d", w.Code)
2024 }
2025 case <-time.After(10 * time.Second):
2026 t.Fatal("a request waits for a read past its time of 200ms")
2027 }
2028
2029 // A request whose reader goes away stops waiting, and answers
2030 // nothing.
2031 h.srv.timeout = time.Hour
2032 fourth := h.publish(exporttest.SignedAt.Add(3*time.Minute), nil, renamed("Readers browse the fourth plan"))
2033 ctx, cancel := context.WithCancel(context.Background())
2034 defer cancel()
2035 gone := serve(httptest.NewRequest("GET", "/", nil).WithContext(ctx))
2036 eventually(t, "a request waits for the fourth generation", func() bool { return len(h.srv.loadWaiting) == 3 })
2037 cancel()
2038 select {
2039 case w := <-gone:
2040 if w.Body.Len() != 0 {
2041 t.Errorf("a request whose reader went away answered %d", w.Code)
2042 }
2043 case <-time.After(10 * time.Second):
2044 t.Fatal("a request whose reader went away still waits")
2045 }
2046
2047 h.srv.mu.Lock()
2048 left := len(h.srv.loads)
2049 h.srv.mu.Unlock()
2050 if left != MaxLoads {
2051 t.Errorf("%d loads may be joined; only the %d that run are wanted", left, MaxLoads)
2052 }
2053 h.publish(exporttest.SignedAt.Add(4*time.Minute), nil, renamed("Readers browse the fifth plan"))
2054 for _, g := range []export.Generation{third, fourth} {
2055 if _, err := os.Stat(g.Dir); !os.IsNotExist(err) {
2056 t.Errorf("generation %d outlived an activation after its request gave up: %v", g.Sequence, err)
2057 }
2058 }
2059
2060 // The first two reads end, and their requests are served the newest
2061 // generation.
2062 close(hold)
2063 expect(firstServed, "Readers browse the fifth plan")
2064 expect(secondServed, "Readers browse the fifth plan")
2065 for _, g := range []export.Generation{third, fourth} {
2066 if n := loaded(g); n != 0 {
2067 t.Errorf("generation %d's export was read %d times after every request for it gave up", g.Sequence, n)
2068 }
2069 }
2070 mu.Lock()
2071 defer mu.Unlock()
2072 if len(logged) != 1 || !strings.Contains(logged[0], "deadline exceeded") {
2073 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
2074 }
2075}
2076
2077// A load that reads slowly does not hold the request that waits for it:
2078// the request answers 503 at its deadline. With no request left waiting,
2079// the load stops reading part way through the export, caches nothing, and
2080// gives back its generation, which the next activation deletes. A load
2081// that ends is kept, and the requests after it are served without another
2082// read.
2083func TestSlowLoadEndsWithItsRequests(t *testing.T) {
2084 h := newHarness(t)
2085 h.srv.timeout = 200 * time.Millisecond
2086 var mu sync.Mutex
2087 var logged []string
2088 h.srv.log = func(err error) {
2089 mu.Lock()
2090 defer mu.Unlock()
2091 logged = append(logged, err.Error())
2092 }
2093 var reads atomic.Int32
2094 h.srv.loading = func(export.Generation) { reads.Add(1) }
2095
2096 // The active generation's export.json becomes a pipe the test writes
2097 // a few bytes at a time, as a slow disk would give it: all of it
2098 // takes about 4 seconds, twenty times the request's time.
2099 old := h.active()
2100 data, err := os.ReadFile(old.ExportPath())
2101 if err != nil {
2102 t.Fatal(err)
2103 }
2104 if err := os.Remove(old.ExportPath()); err != nil {
2105 t.Fatal(err)
2106 }
2107 if err := syscall.Mkfifo(old.ExportPath(), 0o600); err != nil {
2108 t.Fatal(err)
2109 }
2110 piece := max(1, len(data)/200)
2111 wrote := make(chan error, 1)
2112 go func() {
2113 f, err := os.OpenFile(old.ExportPath(), os.O_WRONLY, 0)
2114 if err != nil {
2115 wrote <- err
2116 return
2117 }
2118 defer f.Close()
2119 for p := data; len(p) > 0; p = p[min(len(p), piece):] {
2120 if _, err := f.Write(p[:min(len(p), piece)]); err != nil {
2121 wrote <- err
2122 return
2123 }
2124 time.Sleep(20 * time.Millisecond)
2125 }
2126 wrote <- nil
2127 }()
2128
2129 start := time.Now()
2130 if w := h.get("/"); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
2131 t.Errorf("a request whose load ran past its time answered %d", w.Code)
2132 }
2133 if waited := time.Since(start); waited > 2*time.Second {
2134 t.Errorf("a request waited %v for a slow load, past its time of 200ms", waited)
2135 }
2136 select {
2137 case err := <-wrote:
2138 if !errors.Is(err, syscall.EPIPE) {
2139 t.Errorf("the load read the whole export after its request gave up: the writer ended with %v", err)
2140 }
2141 case <-time.After(10 * time.Second):
2142 t.Fatal("the load still reads the export")
2143 }
2144 eventually(t, "the load ends", func() bool { return len(h.srv.loaders) == 0 })
2145 h.srv.mu.Lock()
2146 cached, loads := h.srv.cached, len(h.srv.loads)
2147 h.srv.mu.Unlock()
2148 if cached != nil || loads != 0 {
2149 t.Errorf("a load that stopped left a snapshot %v and %d loads", cached != nil, loads)
2150 }
2151 // The store reads the active export.json when it takes an upload.
2152 if err := os.Remove(old.ExportPath()); err != nil {
2153 t.Fatal(err)
2154 }
2155 if err := os.WriteFile(old.ExportPath(), data, 0o644); err != nil {
2156 t.Fatal(err)
2157 }
2158 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
2159 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
2160 t.Errorf("the generation a stopped load opened outlived an activation: %v", err)
2161 }
2162
2163 h.srv.timeout = requestTimeout
2164 for range 3 {
2165 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the second plan") {
2166 t.Error("a request after the stopped load is not served the new generation")
2167 }
2168 }
2169 if n := reads.Load(); n != 2 {
2170 t.Errorf("exports were read %d times: once in part, and once for the new generation", n)
2171 }
2172 mu.Lock()
2173 defer mu.Unlock()
2174 if len(logged) != 1 || !strings.Contains(logged[0], "export to be read: context deadline exceeded") {
2175 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
2176 }
2177}
2178
2179// openFiles is the number of files the process holds open, and false
2180// where the system does not list them.
2181func openFiles(t *testing.T) (int, bool) {
2182 t.Helper()
2183 entries, err := os.ReadDir("/proc/self/fd")
2184 if err != nil {
2185 return 0, false
2186 }
2187 return len(entries), true
2188}
2189
2190// A flood of requests while a load runs: MaxLoadWaiting of them wait, and
2191// the rest answer 503 at once, unlogged. A waiting request holds no
2192// generation, so the goroutines and files the server holds stay within a
2193// bound however large the flood. Once the load ends, every request that
2194// waited is served from its one read.
2195func TestLoadFlood(t *testing.T) {
2196 h := newHarness(t)
2197 var reads atomic.Int32
2198 reading, hold := make(chan struct{}, 1), make(chan struct{})
2199 h.srv.loading = func(export.Generation) {
2200 reads.Add(1)
2201 reading <- struct{}{}
2202 <-hold
2203 }
2204 get := func(n int) chan *httptest.ResponseRecorder {
2205 served := make(chan *httptest.ResponseRecorder, n)
2206 for range n {
2207 go func() {
2208 w := httptest.NewRecorder()
2209 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
2210 served <- w
2211 }()
2212 }
2213 return served
2214 }
2215
2216 first := get(1)
2217 select {
2218 case <-reading:
2219 case <-time.After(10 * time.Second):
2220 t.Fatal("no load started")
2221 }
2222 goroutines := runtime.NumGoroutine()
2223 files, listed := openFiles(t)
2224
2225 flood := 4 * MaxLoadWaiting
2226 served := get(flood)
2227 refused := flood - (MaxLoadWaiting - 1)
2228 for range refused {
2229 if w := <-served; w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
2230 t.Fatalf("a request past MaxLoadWaiting answered %d", w.Code)
2231 }
2232 }
2233 if n := len(h.srv.loadWaiting); n != MaxLoadWaiting {
2234 t.Errorf("%d requests wait for the load, not %d", n, MaxLoadWaiting)
2235 }
2236 const slack = 8
2237 eventually(t, "the refused requests' goroutines end", func() bool {
2238 return runtime.NumGoroutine() <= goroutines+MaxLoadWaiting-1+slack
2239 })
2240 if n, _ := openFiles(t); listed && n > files+slack {
2241 t.Errorf("the flood holds %d files open, %d more than before it", n, n-files)
2242 }
2243
2244 close(hold)
2245 for range MaxLoadWaiting - 1 {
2246 if w := <-served; w.Code != http.StatusOK {
2247 t.Errorf("a request that waited for the load answered %d", w.Code)
2248 }
2249 }
2250 if w := <-first; w.Code != http.StatusOK {
2251 t.Errorf("the request that started the load answered %d", w.Code)
2252 }
2253 if n := reads.Load(); n != 1 {
2254 t.Errorf("the export was read %d times for one generation", n)
2255 }
2256 if n := len(h.srv.loadWaiting); n != 0 {
2257 t.Errorf("%d requests still hold a place among those that wait", n)
2258 }
2259}
2260
2261// A request's time runs from its arrival through its rendering: a request
2262// for a page that runs no git, held past its time before it renders,
2263// answers 503, and the server logs it.
2264func TestRenderingIsWithinTheDeadline(t *testing.T) {
2265 h := newHarness(t)
2266 h.page("/")
2267 h.srv.timeout = 50 * time.Millisecond
2268 var logged []string
2269 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
2270 h.srv.opened = func(export.Generation) { time.Sleep(100 * time.Millisecond) }
2271 if w := h.get("/"); w.Code != http.StatusServiceUnavailable || !bytes.Equal(w.Body.Bytes(), busyPage) {
2272 t.Errorf("a request that ran out of time before it rendered answered %d", w.Code)
2273 }
2274 if len(logged) != 1 || !strings.Contains(logged[0], "rendering plan: context deadline exceeded") {
2275 t.Errorf("the server logged %q", logged)
2276 }
2277 if n, _ := h.srv.holding(); n != 0 {
2278 t.Errorf("a page that stopped rendering kept %d pieces of the budget", n)
2279 }
2280}
2281
2282// A FIFO with a writer that sends no bytes keeps Read blocked until the
2283// request deadline. A FIFO without a writer must not block Open.
2284func TestStalledLoadReleasesGeneration(t *testing.T) {
2285 for _, writer := range []bool{false, true} {
2286 t.Run(fmt.Sprint(writer), func(t *testing.T) {
2287 h := newHarness(t)
2288 h.srv.timeout = 100 * time.Millisecond
2289 h.srv.log = func(error) {}
2290 old := h.active()
2291 data, err := os.ReadFile(old.ExportPath())
2292 if err != nil {
2293 t.Fatal(err)
2294 }
2295 if err := os.Remove(old.ExportPath()); err != nil {
2296 t.Fatal(err)
2297 }
2298 if err := syscall.Mkfifo(old.ExportPath(), 0600); err != nil {
2299 t.Fatal(err)
2300 }
2301 if writer {
2302 f, err := os.OpenFile(old.ExportPath(), os.O_RDWR|syscall.O_NONBLOCK, 0)
2303 if err != nil {
2304 t.Fatal(err)
2305 }
2306 defer f.Close()
2307 if _, err := f.Write([]byte("{")); err != nil {
2308 t.Fatal(err)
2309 }
2310 }
2311 if w := h.get("/"); w.Code != http.StatusServiceUnavailable {
2312 t.Fatalf("status = %d", w.Code)
2313 }
2314 eventually(t, "the stalled worker exits", func() bool { return len(h.srv.loaders) == 0 })
2315 h.srv.mu.Lock()
2316 cached := h.srv.cached
2317 h.srv.mu.Unlock()
2318 if cached != nil {
2319 t.Fatal("stalled load cached a snapshot")
2320 }
2321 if err := os.Remove(old.ExportPath()); err != nil {
2322 t.Fatal(err)
2323 }
2324 if err := os.WriteFile(old.ExportPath(), data, 0644); err != nil {
2325 t.Fatal(err)
2326 }
2327 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan"))
2328 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
2329 t.Fatalf("generation retained: %v", err)
2330 }
2331 h.srv.timeout = requestTimeout
2332 if !strings.Contains(h.page("/app/knots/oc-a000001"), "The second plan") {
2333 t.Fatal("loader slot is not reusable")
2334 }
2335 })
2336 }
2337}
2338
2339// cancelInPhase cancels a real context on the third cancellation check
2340// inside a named processing function. It makes cancellation during CPU
2341// work deterministic without replacing decoding or graph traversal.
2342type cancelInPhase struct {
2343 context.Context
2344 cancel context.CancelFunc
2345 phase string
2346 checks int
2347}
2348
2349func (c *cancelInPhase) Err() error {
2350 var pcs [32]uintptr
2351 n := runtime.Callers(2, pcs[:])
2352 frames := runtime.CallersFrames(pcs[:n])
2353 for {
2354 frame, more := frames.Next()
2355 if strings.HasSuffix(frame.Function, c.phase) {
2356 c.checks++
2357 if c.checks == 3 {
2358 c.cancel()
2359 }
2360 break
2361 }
2362 if !more {
2363 break
2364 }
2365 }
2366 return c.Context.Err()
2367}
2368
2369func TestProcessingCancellationReleasesGeneration(t *testing.T) {
2370 for _, phase := range []string{".decodeValue", ".(*Export).ValidateContext", ".(*index).planPage", ".(*index).paths", ".(*index).milestones"} {
2371 t.Run(phase, func(t *testing.T) {
2372 h := newHarness(t)
2373 old := h.active()
2374 base, cancel := context.WithCancel(context.Background())
2375 defer cancel()
2376 ctx := &cancelInPhase{Context: base, cancel: cancel, phase: phase}
2377 l := &load{done: make(chan struct{}), cancel: cancel}
2378 h.srv.loads[l] = struct{}{}
2379 h.srv.loaders <- struct{}{}
2380 finished := make(chan struct{})
2381 go func() { h.srv.run(ctx, l); close(finished) }()
2382 select {
2383 case <-finished:
2384 case <-time.After(2 * time.Second):
2385 t.Fatal("processing did not stop")
2386 }
2387 if ctx.checks < 3 {
2388 t.Fatalf("phase was not reached: %d checks", ctx.checks)
2389 }
2390 if !errors.Is(l.err, context.Canceled) {
2391 t.Fatalf("load error = %v", l.err)
2392 }
2393 if h.srv.cached != nil || len(h.srv.loaders) != 0 || len(h.srv.loads) != 0 {
2394 t.Fatal("cancelled processing retained load state")
2395 }
2396 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan"))
2397 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
2398 t.Fatalf("generation retained: %v", err)
2399 }
2400 if !strings.Contains(h.page("/app/knots/oc-a000001"), "The second plan") {
2401 t.Fatal("loader slot is not reusable")
2402 }
2403 })
2404 }
2405}