gunk-dev/the-valley

server_test.go

source17bdc72ab78fmain's published tip history
79.2 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 "strings"
21 "sync"
22 "sync/atomic"
23 "syscall"
24 "testing"
25 "time"
26
27 "the-valley/knot"
28 "the-valley/webui/export"
29 "the-valley/webui/export/exporttest"
30)
31
32// harness is a server over a real store that the fixture's export was
33// uploaded to, with a clock the test sets.
34type harness struct {
35 t *testing.T
36 f *exporttest.Fixture
37 store *export.Store
38 srv *Server
39 now time.Time
40}
41
42// newHarness serves the fixture's export, two minutes after it was
43// collected.
44func newHarness(t *testing.T) *harness {
45 t.Helper()
46 f := exporttest.New(t)
47 store, err := export.OpenStore(t.TempDir(), func(err error) { t.Errorf("the store reported: %v", err) })
48 if err != nil {
49 t.Fatal(err)
50 }
51 f.Upload(t, store)
52 h := &harness{t: t, f: f, store: store, now: exporttest.Collected.Add(2 * time.Minute)}
53 h.srv = New(Config{Store: store, Now: func() time.Time { return h.now },
54 Log: func(err error) { t.Errorf("the server logged: %v", err) }})
55 return h
56}
57
58func (h *harness) do(method, target string) *httptest.ResponseRecorder {
59 h.t.Helper()
60 w := httptest.NewRecorder()
61 h.srv.ServeHTTP(w, httptest.NewRequest(method, target, nil))
62 return w
63}
64
65func (h *harness) get(target string) *httptest.ResponseRecorder {
66 h.t.Helper()
67 return h.do("GET", target)
68}
69
70// page is the body of a GET that must answer 200.
71func (h *harness) page(target string) string {
72 h.t.Helper()
73 w := h.get(target)
74 if w.Code != http.StatusOK {
75 h.t.Fatalf("GET %s answered %d:\n%s", target, w.Code, w.Body)
76 }
77 return w.Body.String()
78}
79
80// tip is the fixture's published source tip of app.
81func (h *harness) tip() string { return h.f.Export.Projects[0].SourceTip }
82
83// publish activates a new generation, signed at: the fixture's export
84// changed by change, with the bundles given, by project, in place of the
85// fixture's.
86func (h *harness) publish(at time.Time, bundles map[string]string, change func(*export.Export)) export.Generation {
87 t := h.t
88 t.Helper()
89 e, err := export.Decode(h.f.ExportJSON)
90 if err != nil {
91 t.Fatal(err)
92 }
93 change(e)
94 data, err := e.Encode()
95 if err != nil {
96 t.Fatal(err)
97 }
98 paths := map[string]string{}
99 for _, p := range e.Projects {
100 if paths[p.Name] = bundles[p.Name]; paths[p.Name] == "" {
101 paths[p.Name] = h.f.Bundles[p.Name]
102 }
103 }
104 bodies := map[string]export.Body{}
105 for name, path := range paths {
106 if bodies[name], err = export.FileBody(name, path); err != nil {
107 t.Fatal(err)
108 }
109 }
110 m, err := export.NewManifest(exporttest.Instance, exporttest.Destination, at.UnixNano(), e, data, bodies)
111 if err != nil {
112 t.Fatal(err)
113 }
114 hw, err := h.store.HighWater()
115 if err != nil {
116 t.Fatal(err)
117 }
118 a := h.f.Admission()
119 a.Now, a.HighWater = at.Add(time.Second), hw
120 if m, err = export.VerifyManifest(bytes.NewReader(h.f.Sign(t, m)), a); err != nil {
121 t.Fatal(err)
122 }
123 st, err := h.store.Stage(m)
124 if err != nil {
125 t.Fatal(err)
126 }
127 inv, err := h.store.Inventory(st)
128 if err != nil {
129 t.Fatal(err)
130 }
131 for _, need := range inv.Needs {
132 body := data
133 if need.Name != export.ExportFile {
134 if body, err = os.ReadFile(paths[need.Name]); err != nil {
135 t.Fatal(err)
136 }
137 }
138 req := httptest.NewRequest("PUT", export.BodyPath(m.Sequence, need.SHA256), bytes.NewReader(body))
139 if _, err := export.StageBody(st.Bodies(), export.Body{Name: need.Name, SHA256: need.SHA256, Size: need.Size}, 64<<20, req); err != nil {
140 t.Fatal(err)
141 }
142 }
143 g, err := h.store.Activate(context.Background(), st)
144 if err != nil {
145 t.Fatal(err)
146 }
147 return g
148}
149
150// active is the generation the store serves.
151func (h *harness) active() export.Generation {
152 h.t.Helper()
153 g, release, err := h.store.Open()
154 if err != nil {
155 h.t.Fatal(err)
156 }
157 release()
158 return g
159}
160
161// git runs git on the repository at repo, with no configuration of the
162// caller's and a fixed identity for the commits it writes.
163func git(t *testing.T, repo string, stdin []byte, args ...string) string {
164 t.Helper()
165 cmd := exec.Command(export.GitProgram, append([]string{"--git-dir=" + repo}, args...)...)
166 for _, kv := range os.Environ() {
167 if !strings.HasPrefix(kv, "GIT_") {
168 cmd.Env = append(cmd.Env, kv)
169 }
170 }
171 cmd.Env = append(cmd.Env, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
172 "GIT_AUTHOR_NAME=Example Author", "GIT_AUTHOR_EMAIL=author@example.org", "GIT_AUTHOR_DATE=1791190800 +0000",
173 "GIT_COMMITTER_NAME=Example Author", "GIT_COMMITTER_EMAIL=author@example.org", "GIT_COMMITTER_DATE=1791190800 +0000")
174 if stdin != nil {
175 cmd.Stdin = bytes.NewReader(stdin)
176 }
177 var stderr bytes.Buffer
178 cmd.Stderr = &stderr
179 out, err := cmd.Output()
180 if err != nil {
181 t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, stderr.String())
182 }
183 return strings.TrimSpace(string(out))
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 + "?skip=-1",
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 if !strings.Contains(page, `href="/app/source/log/`+tip+`?skip=1"`) {
722 t.Error("the page that ends early does not link the commits after the one it cut")
723 }
724 page = h.page(at + "?skip=1")
725 if strings.Contains(page, "ends early") || !strings.Contains(page, "long: a long subject") || !strings.Contains(page, "app: the first README") {
726 t.Errorf("the next page of history is not whole:\n%s", page)
727 }
728 if strings.Contains(page, strings.Repeat("a long subject ", (maxLogText/15)+1)) {
729 t.Error("a subject longer than a page shows is not cut")
730 }
731 for _, p := range []string{at, at + "?skip=1"} {
732 if n := len(h.page(p)); n > 64<<10 {
733 t.Errorf("GET %s is %d bytes", p, n)
734 }
735 }
736}
737
738// The directories along a path share one budget of MaxRead bytes of git
739// ls-tree's output. Each of big/ and big/zz/ lists about 3 MB before
740// the entry the path names next, within MaxRead alone, so the directory
741// big/zz/ is served. A path through both, to big/zz/zz/f, passes the
742// budget and answers 404. The directory's own listing has a budget of
743// its own.
744func TestResolveSharesOneBudget(t *testing.T) {
745 h := newHarness(t)
746 name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) }
747 var files []file
748 for i := range 10_000 {
749 files = append(files, file{"100644", "big/" + name(i), "x\n"}, file{"100644", "big/zz/" + name(i), "x\n"})
750 }
751 files = append(files, file{"100644", "big/zz/zz/f", "the file\n"})
752 if each := 6 + 1 + 4 + 1 + 40 + 1 + 246 + 1; 10_000*each > MaxRead || 2*10_000*each <= MaxRead {
753 t.Fatalf("the listings take %d bytes each, not between half MaxRead and MaxRead", 10_000*each)
754 }
755 tip, bundle := h.commitMain("app: two large directories, one in the other\n", files...)
756 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
757
758 h.page("/app/source/tree/" + tip + "/big/zz/")
759 h.page("/app/source/blob/" + tip + "/big/zz/" + name(0))
760 for _, target := range []string{"/app/source/tree/" + tip + "/big/zz/zz/", "/app/source/blob/" + tip + "/big/zz/zz/f"} {
761 if w := h.get(target); w.Code != http.StatusNotFound {
762 t.Errorf("GET %s, through %d bytes of listings, answered %d", target, 2*10_000*300, w.Code)
763 }
764 }
765}
766
767// A page of history skips at most MaxSkip commits. The page at MaxSkip
768// links the commits older than it as the history that ends at its last
769// commit, less that commit, and that page is served.
770func TestLogSkipIsBounded(t *testing.T) {
771 h := newHarness(t)
772 repo := h.f.Repos["app"]
773 var b bytes.Buffer
774 who := "Example Author <author@example.org> 1791190800 +0000"
775 n := MaxSkip + LogPage + 10
776 for i := range n {
777 fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who)
778 msg := fmt.Sprintf("commit %d\n", i)
779 fmt.Fprintf(&b, "data %d\n%s\n", len(msg), msg)
780 if i == 0 {
781 fmt.Fprintf(&b, "from %s\n", git(t, repo, nil, "rev-parse", export.MainRef))
782 }
783 }
784 git(t, repo, b.Bytes(), "fast-import", "--quiet")
785 tip := git(t, repo, nil, "rev-parse", export.MainRef)
786 bundle := filepath.Join(t.TempDir(), "app.bundle")
787 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
788 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
789
790 at := "/app/source/log/" + tip
791 if page := h.page(at + fmt.Sprintf("?skip=%d", MaxSkip-LogPage)); !strings.Contains(page, fmt.Sprintf(`href="%s?skip=%d"`, at, MaxSkip)) {
792 t.Errorf("the page before MaxSkip does not link the page at it")
793 }
794 page := h.page(at + fmt.Sprintf("?skip=%d", MaxSkip))
795 // The page at MaxSkip shows commits n-1-MaxSkip down to
796 // n-MaxSkip-LogPage, the last of them, counting from the oldest new
797 // commit as 0.
798 last := git(t, repo, nil, "rev-parse", fmt.Sprintf("%s~%d", tip, MaxSkip+LogPage-1))
799 older := "/app/source/log/" + last + "?skip=1"
800 if !strings.Contains(page, `href="`+older+`"`) {
801 t.Errorf("the page at MaxSkip does not link its older commits as the history of %s", last)
802 }
803 page = h.page(older)
804 if !strings.Contains(page, fmt.Sprintf("commit %d<", n-MaxSkip-LogPage-1)) || !strings.Contains(page, "app: the first README") {
805 t.Errorf("the history past MaxSkip is not served:\n%s", page)
806 }
807 if strings.Contains(page, fmt.Sprintf("commit %d<", n-MaxSkip-LogPage)) {
808 t.Error("the history past MaxSkip shows the commit it starts after")
809 }
810 if w := h.get(at + fmt.Sprintf("?skip=%d", MaxSkip+1)); w.Code != http.StatusNotFound {
811 t.Errorf("a page skipping past MaxSkip answered %d", w.Code)
812 }
813}
814
815// A source request's git commands have a bound of their own, far within
816// the request's time: a git that does not finish is stopped once it
817// passes, and the request answers 503 and gives back its git slot. The
818// failure is logged.
819func TestSourceGitHasItsOwnBound(t *testing.T) {
820 h := newHarness(t)
821 real, err := exec.LookPath(export.GitProgram)
822 if err != nil {
823 t.Fatal(err)
824 }
825 if real, err = filepath.Abs(real); err != nil {
826 t.Fatal(err)
827 }
828 slow := filepath.Join(t.TempDir(), "git")
829 script := "#!/bin/sh\nfor a; do [ \"$a\" = ls-tree ] && exec sleep 60; done\nexec '" + real + "' \"$@\"\n"
830 if err := os.WriteFile(slow, []byte(script), 0o755); err != nil {
831 t.Fatal(err)
832 }
833 program := export.GitProgram
834 export.GitProgram = slow
835 t.Cleanup(func() { export.GitProgram = program })
836 var logged []error
837 var mu sync.Mutex
838 h.srv.log = func(err error) { mu.Lock(); logged = append(logged, err); mu.Unlock() }
839 h.srv.gitTime = 300 * time.Millisecond
840
841 start := time.Now()
842 w := h.get("/app/source/tree/" + h.tip() + "/")
843 if took := time.Since(start); w.Code != http.StatusServiceUnavailable || took > 5*time.Second {
844 t.Errorf("a source request whose git does not finish answered %d after %v", w.Code, took)
845 }
846 if len(h.srv.slots) != 0 {
847 t.Errorf("the request holds %d git slots once it answered", len(h.srv.slots))
848 }
849 mu.Lock()
850 defer mu.Unlock()
851 if len(logged) != 1 || !strings.Contains(logged[0].Error(), "the request held its git slot past 300ms") {
852 t.Errorf("the server logged %v", logged)
853 }
854 if w := h.get("/app/knots/oc-a000002"); w.Code != http.StatusOK {
855 t.Errorf("a knot answered %d", w.Code)
856 }
857}
858
859// A source request's bound on its git slot runs from when it takes the
860// slot, and covers its wait for its generation's export to be read. A
861// source request whose export is read slowly answers 503 once the bound
862// passes, gives back its slot, and is logged, while a request for the
863// plan, which holds no slot, waits on for the same read and is served.
864func TestGitSlotBoundCoversTheLoad(t *testing.T) {
865 h := newHarness(t)
866 var mu sync.Mutex
867 var logged []error
868 h.srv.log = func(err error) { mu.Lock(); logged = append(logged, err); mu.Unlock() }
869 h.srv.gitTime = 300 * time.Millisecond
870 hold := make(chan struct{})
871 h.srv.loading = func(export.Generation) { <-hold }
872
873 plan := make(chan *httptest.ResponseRecorder, 1)
874 go func() {
875 w := httptest.NewRecorder()
876 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
877 plan <- w
878 }()
879 eventually(t, "the plan waits for the export to be read", func() bool { return len(h.srv.loaders) == 1 })
880 start := time.Now()
881 w := h.get("/app/source/tree/" + h.tip() + "/")
882 if took := time.Since(start); w.Code != http.StatusServiceUnavailable || took > 5*time.Second {
883 t.Errorf("a source request whose export is read slowly answered %d after %v", w.Code, took)
884 }
885 if len(h.srv.slots) != 0 {
886 t.Errorf("the request holds %d git slots once it answered", len(h.srv.slots))
887 }
888 mu.Lock()
889 if len(logged) != 1 || !strings.Contains(logged[0].Error(), "the request held its git slot past 300ms") ||
890 !strings.Contains(logged[0].Error(), "export to be read") {
891 t.Errorf("the server logged %v", logged)
892 }
893 mu.Unlock()
894
895 close(hold)
896 select {
897 case w := <-plan:
898 if w.Code != http.StatusOK {
899 t.Errorf("the plan answered %d once its export was read", w.Code)
900 }
901 case <-time.After(10 * time.Second):
902 t.Fatal("the plan was not served once its export was read")
903 }
904 h.page("/app/source/tree/" + h.tip() + "/")
905}
906
907// A source request gives back its git slot before it renders its page, so
908// a page that renders slowly holds no slot, and is not held to the bound
909// on holding one. While one renders, past that bound, another source
910// request is served, and the first is served in full once it renders.
911func TestRenderingHoldsNoGitSlot(t *testing.T) {
912 h := newHarness(t)
913 h.page("/")
914 h.srv.gitTime = 300 * time.Millisecond
915 rendering, hold := make(chan struct{}), make(chan struct{})
916 var first atomic.Bool
917 h.srv.rendering = func(name string) {
918 if name == "tree" && first.CompareAndSwap(false, true) {
919 close(rendering)
920 <-hold
921 }
922 }
923
924 served := make(chan *httptest.ResponseRecorder, 1)
925 go func() {
926 w := httptest.NewRecorder()
927 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/source/tree/"+h.tip()+"/", nil))
928 served <- w
929 }()
930 select {
931 case <-rendering:
932 case <-time.After(10 * time.Second):
933 t.Fatal("the source request did not render")
934 }
935 if len(h.srv.slots) != 0 {
936 t.Errorf("a source request holds %d git slots while it renders", len(h.srv.slots))
937 }
938 h.page("/app/source/blob/" + h.tip() + "/docs/guide.md")
939 time.Sleep(2 * h.srv.gitTime)
940 close(hold)
941 select {
942 case w := <-served:
943 if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "guide.md") {
944 t.Errorf("a source request that rendered past the bound on its slot answered %d", w.Code)
945 }
946 case <-time.After(10 * time.Second):
947 t.Fatal("the source request was not served once it rendered")
948 }
949}
950
951// A SHA-256 project's commits are served by their 64 hex digits alone.
952// The first 40 of them, which git would read as an abbreviation, answer
953// 404 on every source route, so each page has one address.
954func TestSHA256CommitIDs(t *testing.T) {
955 h := newHarness(t)
956 repo := filepath.Join(t.TempDir(), "app.git")
957 git(t, repo, nil, "init", "--quiet", "--bare", "--template=", "--initial-branch=main", "--object-format=sha256")
958 readme := "# app\n\nA SHA-256 repository.\n"
959 who := "Example Author <author@example.org> 1791190800 +0000"
960 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",
961 who, who, len(readme), readme)
962 git(t, repo, []byte(stream), "fast-import", "--quiet")
963 tip := git(t, repo, nil, "rev-parse", export.MainRef)
964 if len(tip) != 64 {
965 t.Fatalf("the tip is %q", tip)
966 }
967 bundle := filepath.Join(t.TempDir(), "app.bundle")
968 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
969 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
970
971 for _, route := range []string{"/app/source/tree/%s/", "/app/source/blob/%s/README.md", "/app/source/log/%s"} {
972 if page := h.page(fmt.Sprintf(route, tip)); !strings.Contains(page, tip[:12]) {
973 t.Errorf("%s does not name the commit", fmt.Sprintf(route, tip))
974 }
975 if w := h.get(fmt.Sprintf(route, tip[:40])); w.Code != http.StatusNotFound {
976 t.Errorf("%s answered %d", fmt.Sprintf(route, tip[:40]), w.Code)
977 }
978 }
979 if w := h.get("/app/source/"); w.Header().Get("Location") != "/app/source/tree/"+tip+"/" {
980 t.Errorf("/app/source/ redirects to %q", w.Header().Get("Location"))
981 }
982}
983
984// A file of exactly MaxFile bytes of newlines is shown to MaxLines lines,
985// and its page says where it stops. A README longer than a page shows is
986// shown in part.
987func TestLongFileIsShownInPart(t *testing.T) {
988 h := newHarness(t)
989 tip, bundle := h.commitMain("app: long files\n",
990 file{"100644", "newlines.txt", strings.Repeat("\n", MaxFile)},
991 file{"100644", "long/README.md", strings.Repeat("a line of the README\n", 2*MaxLines)},
992 file{"100644", "wide.txt", strings.Repeat("<", MaxFile)},
993 )
994 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
995
996 page := h.page("/app/source/blob/" + tip + "/newlines.txt")
997 last := fmt.Sprintf(`id="L%d"`, MaxLines)
998 if !strings.Contains(page, last) || strings.Contains(page, fmt.Sprintf(`id="L%d"`, MaxLines+1)) {
999 t.Errorf("the file of newlines is not shown to line %d", MaxLines)
1000 }
1001 if want := fmt.Sprintf("The page stops at line %d of %d.", MaxLines, MaxFile); !strings.Contains(page, want) {
1002 t.Errorf("the page does not say %q", want)
1003 }
1004 if len(page) > MaxShown {
1005 t.Errorf("the page of a file of newlines is %d bytes, past MaxShown", len(page))
1006 }
1007
1008 // One line of MaxFile characters that each escape to four bytes is
1009 // cut where MaxShown is reached.
1010 page = h.page("/app/source/blob/" + tip + "/wide.txt")
1011 if !strings.Contains(page, "The page stops at line 1 of 1.") || len(page) > MaxShown+64<<10 {
1012 t.Errorf("the page of one wide line is %d bytes", len(page))
1013 }
1014
1015 page = h.page("/app/source/tree/" + tip + "/long/")
1016 if !strings.Contains(page, "This README is longer than a page shows, and only its start is shown.") {
1017 t.Error("the long README is not marked as shown in part")
1018 }
1019 if n := strings.Count(page, "a line of the README"); n != MaxLines {
1020 t.Errorf("the long README shows %d lines, not %d", n, MaxLines)
1021 }
1022}
1023
1024// A chain of knots as deep as the graph's knot limit allows renders its
1025// milestone to MaxPlanDepth levels, counts every knot under it, and
1026// names MaxPlanDepth parents in the deepest knot's trail. The plan page's
1027// structure is built once for the generation. Siblings that block one
1028// another in a cycle share the last stage of their path.
1029func TestDeepPlan(t *testing.T) {
1030 h := newHarness(t)
1031 var chain []string
1032 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
1033 p := &e.Projects[0]
1034 for i := range knot.MaxKnots - len(p.Knots) - 3 {
1035 id := fmt.Sprintf("oc-c%06x", i)
1036 k := export.Knot{ID: id, Type: "outcome", Status: "open", Active: true, State: "ready",
1037 Title: fmt.Sprintf("Level %d of the chain", i), Created: "2026-10-01", CreatedBy: "operator"}
1038 if i == 0 {
1039 p.Roots = append(p.Roots, id)
1040 } else {
1041 k.Parent = chain[i-1]
1042 p.Knots[len(p.Knots)-1].Children = []string{id}
1043 }
1044 chain = append(chain, id)
1045 p.Knots = append(p.Knots, k)
1046 }
1047 // Under the first link, a path whose two last siblings wait on
1048 // each other.
1049 free, a, b := "oc-d000001", "oc-d000002", "oc-d000003"
1050 for _, k := range []export.Knot{
1051 {ID: free, BlockedBy: []string{}},
1052 {ID: a, BlockedBy: []string{free, b}},
1053 {ID: b, BlockedBy: []string{a}},
1054 } {
1055 k.Type, k.Status, k.State, k.Title, k.Parent = "outcome", "open", "blocked", "Sibling "+k.ID, chain[0]
1056 p.Knots = append(p.Knots, k)
1057 }
1058 for i := range p.Knots {
1059 if p.Knots[i].ID == chain[0] {
1060 p.Knots[i].Children = append(p.Knots[i].Children, free, a, b)
1061 }
1062 }
1063 })
1064
1065 page := h.page("/")
1066 if want := fmt.Sprintf("%d of %d done", 0, len(chain)-1+3); !strings.Contains(page, want) {
1067 t.Errorf("the chain's milestone does not count every knot under it as %q", want)
1068 }
1069 if !strings.Contains(page, `href="/app/knots/`+chain[MaxPlanDepth]+`"`) || strings.Contains(page, `href="/app/knots/`+chain[MaxPlanDepth+1]+`"`) {
1070 t.Errorf("the chain's tree is not shown to %d levels", MaxPlanDepth)
1071 }
1072 if n := strings.Count(page, ">more on its page<"); n != 1 {
1073 t.Errorf("%d rows say there is more on their page; the chain's deepest shown row does", n)
1074 }
1075 if len(page) > 256<<10 {
1076 t.Errorf("the plan page is %d bytes", len(page))
1077 }
1078 paths := section(t, page, `id="paths-h"`, `id="ms-h"`)
1079 stage := regexp.MustCompile(`<span class="stage-num">(\d+)</span><ul class="plain">(.*?)</ul>`)
1080 var stages []string
1081 for _, m := range stage.FindAllStringSubmatch(paths, -1) {
1082 if strings.Contains(m[2], "Sibling") {
1083 var ids []string
1084 for _, id := range regexp.MustCompile(`"mono muted">(oc-d00000\d)<`).FindAllStringSubmatch(m[2], -1) {
1085 ids = append(ids, id[1])
1086 }
1087 stages = append(stages, m[1]+":"+strings.Join(ids, ","))
1088 }
1089 }
1090 if got := strings.Join(stages, " "); got != "1:oc-d000001 2:oc-d000002,oc-d000003" {
1091 t.Errorf("the siblings' path has stages %q", got)
1092 }
1093
1094 h.srv.mu.Lock()
1095 plan := h.srv.cached.idx.plan
1096 h.srv.mu.Unlock()
1097 h.page("/")
1098 h.srv.mu.Lock()
1099 again := h.srv.cached.idx.plan
1100 h.srv.mu.Unlock()
1101 if plan != again {
1102 t.Error("the plan page's structure was built again for the same generation")
1103 }
1104
1105 deepest := chain[len(chain)-1]
1106 page = h.page("/app/knots/" + deepest)
1107 trail := section(t, page, `<nav class="trail"`, `</nav>`)
1108 if n := strings.Count(trail, `<a href="/app/knots/`); n != MaxPlanDepth || !strings.Contains(trail, "<span>…</span>") {
1109 t.Errorf("the deepest knot's trail names %d parents, or does not mark those above them", n)
1110 }
1111 if !strings.Contains(trail, chain[len(chain)-2]) || strings.Contains(trail, `"/app/knots/`+chain[len(chain)-2-MaxPlanDepth]+`"`) {
1112 t.Error("the trail does not name the nearest parents alone")
1113 }
1114}
1115
1116// Every response carries the strict policy, and the policy admits the
1117// page's one inline stylesheet and one inline script by their hashes and
1118// nothing from another origin.
1119func TestEveryResponseCarriesTheCSP(t *testing.T) {
1120 h := newHarness(t)
1121 for _, c := range []struct{ method, target string }{
1122 {"GET", "/"},
1123 {"GET", "/app/knots/oc-a000002"},
1124 {"GET", "/app/source/"},
1125 {"GET", "/app/source/tree/" + h.tip() + "/"},
1126 {"GET", "/app/source/blob/" + h.tip() + "/README.md"},
1127 {"GET", "/no/such/page"},
1128 {"POST", "/"},
1129 {"HEAD", "/"},
1130 } {
1131 w := h.do(c.method, c.target)
1132 got := w.Header().Get("Content-Security-Policy")
1133 if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" {
1134 t.Errorf("%s %s answered with policy %q", c.method, c.target, got)
1135 }
1136 }
1137 for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} {
1138 if !strings.Contains(csp, directive) {
1139 t.Errorf("the policy lacks %s", directive)
1140 }
1141 }
1142 for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} {
1143 if strings.Contains(csp, loose) {
1144 t.Errorf("the policy holds %q", loose)
1145 }
1146 }
1147
1148 page := h.page("/")
1149 inline := func(tag string) string {
1150 t.Helper()
1151 m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1)
1152 if len(m) != 1 || strings.Count(page, "<"+tag) != 1 {
1153 t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag)
1154 }
1155 sum := sha256.Sum256([]byte(m[0][1]))
1156 return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
1157 }
1158 if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") {
1159 t.Errorf("the policy does not admit the page's script, %s", hash)
1160 }
1161 if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") {
1162 t.Errorf("the policy does not admit the page's stylesheet, %s", hash)
1163 }
1164 for _, external := range []string{"<link", " src=", "@import", "url("} {
1165 if strings.Contains(page, external) {
1166 t.Errorf("the plan page holds %q", external)
1167 }
1168 }
1169}
1170
1171// A request serves everything from the generation it opened, though
1172// another activates while it runs, and that generation outlives the
1173// activation until the request releases it.
1174func TestARequestKeepsItsGeneration(t *testing.T) {
1175 h := newHarness(t)
1176 paused, resume := make(chan export.Generation), make(chan struct{})
1177 var once sync.Once
1178 h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) }
1179 served := make(chan *httptest.ResponseRecorder)
1180 go func() {
1181 w := httptest.NewRecorder()
1182 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/knots/oc-a000001", nil))
1183 served <- w
1184 }()
1185 old := <-paused
1186
1187 next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1188 if next.Sequence == old.Sequence {
1189 t.Fatal("the publish did not activate a new generation")
1190 }
1191 if _, err := os.Stat(old.Dir); err != nil {
1192 t.Fatalf("the generation a request holds was deleted: %v", err)
1193 }
1194 close(resume)
1195 w := <-served
1196 if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app&#39;s plan") || strings.Contains(body, "second plan") {
1197 t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body)
1198 }
1199 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the second plan") {
1200 t.Error("the next request does not serve the new generation")
1201 }
1202
1203 // Released, the old generation goes with the next activation.
1204 h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1205 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1206 t.Errorf("the released generation is still on disk: %v", err)
1207 }
1208}
1209
1210// eventually waits up to ten seconds for cond to hold.
1211func eventually(t *testing.T, what string, cond func() bool) {
1212 t.Helper()
1213 for deadline := time.Now().Add(10 * time.Second); !cond(); time.Sleep(time.Millisecond) {
1214 if time.Now().After(deadline) {
1215 t.Fatalf("timed out waiting until %s", what)
1216 }
1217 }
1218}
1219
1220// renamed changes the title of the fixture's first knot.
1221func renamed(title string) func(*export.Export) {
1222 return func(e *export.Export) { e.Projects[0].Knots[0].Title = title }
1223}
1224
1225// Requests that wait for a generation together read its export once.
1226// While it is read, a newer generation is read on its own, and at most
1227// MaxLoads exports are read at once. A request whose load ends after a
1228// newer generation was activated waits for that one, so every request is
1229// served the generation active when its snapshot is ready, and an older
1230// read that finishes last does not displace the newest snapshot.
1231func TestExportLoadsCoalesce(t *testing.T) {
1232 h := newHarness(t)
1233 var mu sync.Mutex
1234 loads := map[int64]int{}
1235 holds := map[int64]chan struct{}{}
1236 hold := func(g export.Generation) chan struct{} {
1237 mu.Lock()
1238 defer mu.Unlock()
1239 if holds[g.Sequence] == nil {
1240 holds[g.Sequence] = make(chan struct{})
1241 }
1242 return holds[g.Sequence]
1243 }
1244 h.srv.loading = func(g export.Generation) {
1245 mu.Lock()
1246 loads[g.Sequence]++
1247 mu.Unlock()
1248 <-hold(g)
1249 }
1250 loaded := func(g export.Generation) int {
1251 mu.Lock()
1252 defer mu.Unlock()
1253 return loads[g.Sequence]
1254 }
1255 var opens atomic.Int32
1256 h.srv.opened = func(export.Generation) { opens.Add(1) }
1257 get := func(n int) chan *httptest.ResponseRecorder {
1258 served := make(chan *httptest.ResponseRecorder, n)
1259 for range n {
1260 go func() {
1261 w := httptest.NewRecorder()
1262 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/knots/oc-a000001", nil))
1263 served <- w
1264 }()
1265 }
1266 return served
1267 }
1268 expect := func(served chan *httptest.ResponseRecorder, n int, title string) {
1269 t.Helper()
1270 for range n {
1271 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
1272 t.Errorf("a request answered %d, not with %q", w.Code, title)
1273 }
1274 }
1275 }
1276 waiting := func(n int) func() bool { return func() bool { return len(h.srv.loadWaiting) == n } }
1277
1278 first := h.active()
1279 firstServed := get(10)
1280 eventually(t, "ten requests wait for the first generation's read", func() bool {
1281 return loaded(first) == 1 && len(h.srv.loadWaiting) == 10
1282 })
1283 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1284 secondServed := get(1)
1285 eventually(t, "the second generation is read", func() bool { return loaded(second) == 1 })
1286
1287 // Both loaders are taken, so the third generation waits for one.
1288 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1289 thirdServed := get(1)
1290 eventually(t, "a request waits for the third generation", waiting(12))
1291 time.Sleep(20 * time.Millisecond)
1292 if n := loaded(third); n != 0 {
1293 t.Errorf("a third export was read while %d were", MaxLoads)
1294 }
1295 if n := opens.Load(); n != 0 {
1296 t.Errorf("%d requests opened a generation while they waited for its read", n)
1297 }
1298
1299 // The second read ends, and its request finds the third generation
1300 // active, and waits for that read with the third's request.
1301 close(hold(second))
1302 eventually(t, "the third generation is read", func() bool { return loaded(third) == 1 })
1303 close(hold(third))
1304 expect(secondServed, 1, "Readers browse the third plan")
1305 expect(thirdServed, 1, "Readers browse the third plan")
1306 close(hold(first))
1307 expect(firstServed, 10, "Readers browse the third plan")
1308
1309 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the third plan") {
1310 t.Error("the first generation's read displaced the third's")
1311 }
1312 for _, g := range []export.Generation{first, second, third} {
1313 if n := loaded(g); n != 1 {
1314 t.Errorf("generation %d's export was read %d times", g.Sequence, n)
1315 }
1316 }
1317}
1318
1319// Source requests past MaxGit wait, MaxWaiting of them, and one more
1320// answers 503 at once. A waiting request holds no generation, so an
1321// activation while the server is saturated deletes the old generation,
1322// and every waiting request serves the new one. A request's time runs
1323// from its arrival, so one that waits past it answers 503.
1324func TestSourceAdmission(t *testing.T) {
1325 h := newHarness(t)
1326 // The requests that hold the slots wait for the test, not for git, so
1327 // the bound on holding a slot is no part of this test.
1328 h.srv.gitTime = time.Hour
1329 var admitted atomic.Int32
1330 release := make(chan struct{})
1331 h.srv.admitted = func() {
1332 admitted.Add(1)
1333 <-release
1334 }
1335 target := "/app/source/tree/" + h.tip() + "/"
1336 get := func(n int) chan *httptest.ResponseRecorder {
1337 served := make(chan *httptest.ResponseRecorder, n)
1338 for range n {
1339 go func() {
1340 w := httptest.NewRecorder()
1341 h.srv.ServeHTTP(w, httptest.NewRequest("GET", target, nil))
1342 served <- w
1343 }()
1344 }
1345 return served
1346 }
1347
1348 old := h.active()
1349 served := get(MaxGit + MaxWaiting)
1350 eventually(t, "every slot is taken and MaxWaiting requests wait", func() bool {
1351 return admitted.Load() == MaxGit && len(h.srv.waiting) == MaxWaiting
1352 })
1353 if w := h.get(target); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1354 t.Errorf("a source request past MaxWaiting answered %d, Retry-After %q", w.Code, w.Header().Get("Retry-After"))
1355 }
1356 h.page("/") // a page that runs no git is served still
1357
1358 tip, bundle := h.commitMain("app: a commit while the server is saturated\n", file{"100644", "saturated.txt", "saturated\n"})
1359 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1360 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1361 t.Errorf("a generation no request had opened outlived the activation: %v", err)
1362 }
1363 close(release)
1364 for range MaxGit + MaxWaiting {
1365 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "/app/source/tree/"+tip+"/") {
1366 t.Errorf("a waiting request answered %d, not from the new generation", w.Code)
1367 }
1368 }
1369
1370 // A request that waits past its time answers 503. Those that held
1371 // the slots meanwhile ran out of time too.
1372 h.srv.timeout = 200 * time.Millisecond
1373 h.srv.log = func(error) {}
1374 admitted.Store(0)
1375 release = make(chan struct{})
1376 held := get(MaxGit)
1377 eventually(t, "every slot is taken", func() bool { return admitted.Load() == MaxGit })
1378 start := time.Now()
1379 if w := h.get(target); w.Code != http.StatusServiceUnavailable {
1380 t.Errorf("a request that waited past its time answered %d", w.Code)
1381 }
1382 if waited := time.Since(start); waited > 5*time.Second {
1383 t.Errorf("a request waited %v past its time of 200ms", waited)
1384 }
1385 close(release)
1386 for range MaxGit {
1387 if w := <-held; w.Code != http.StatusServiceUnavailable {
1388 t.Errorf("a request that ran out of time answered %d", w.Code)
1389 }
1390 }
1391}
1392
1393// stallingListener accepts connections whose writes stall until release
1394// is closed, while stall is set. Each sends on stalled the first time one
1395// of its writes stalls.
1396type stallingListener struct {
1397 net.Listener
1398 stall atomic.Bool
1399 release chan struct{}
1400 stalled chan struct{}
1401}
1402
1403func (l *stallingListener) Accept() (net.Conn, error) {
1404 c, err := l.Listener.Accept()
1405 if err != nil || !l.stall.Load() {
1406 return c, err
1407 }
1408 return &stallingConn{Conn: c, l: l}, nil
1409}
1410
1411type stallingConn struct {
1412 net.Conn
1413 l *stallingListener
1414 once sync.Once
1415}
1416
1417func (c *stallingConn) Write(p []byte) (int, error) {
1418 c.once.Do(func() { c.l.stalled <- struct{}{} })
1419 <-c.l.release
1420 return c.Conn.Write(p)
1421}
1422
1423// Readers that never read their responses hold no git slot and no
1424// generation: more of them than MaxGit and MaxWaiting together are
1425// stalled writing, and a new reader is still served, and an activation
1426// deletes the generation they were served from.
1427func TestSlowReadersHoldNothing(t *testing.T) {
1428 h := newHarness(t)
1429 ln, err := net.Listen("tcp", "127.0.0.1:0")
1430 if err != nil {
1431 t.Fatal(err)
1432 }
1433 n := MaxGit + MaxWaiting + 4
1434 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
1435 sl.stall.Store(true)
1436 srv := &http.Server{Handler: h.srv}
1437 go srv.Serve(sl)
1438 var conns []net.Conn
1439 defer func() {
1440 close(sl.release)
1441 for _, c := range conns {
1442 c.Close()
1443 }
1444 srv.Close()
1445 }()
1446
1447 old := h.active()
1448 target := "/app/source/blob/" + h.tip() + "/docs/guide.md"
1449 for range n {
1450 c, err := net.Dial("tcp", ln.Addr().String())
1451 if err != nil {
1452 t.Fatal(err)
1453 }
1454 conns = append(conns, c)
1455 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
1456 }
1457 for i := range n {
1458 select {
1459 case <-sl.stalled:
1460 case <-time.After(10 * time.Second):
1461 t.Fatalf("%d of %d slow readers' responses were written; the rest wait", i, n)
1462 }
1463 }
1464 sl.stall.Store(false)
1465 if len(h.srv.slots) != 0 || len(h.srv.waiting) != 0 {
1466 t.Errorf("slow readers hold %d git slots, and %d requests wait", len(h.srv.slots), len(h.srv.waiting))
1467 }
1468
1469 client := &http.Client{Timeout: 10 * time.Second}
1470 resp, err := client.Get("http://" + ln.Addr().String() + target)
1471 if err != nil {
1472 t.Fatal(err)
1473 }
1474 resp.Body.Close()
1475 if resp.StatusCode != http.StatusOK {
1476 t.Errorf("a new reader answered %d while slow readers stall", resp.StatusCode)
1477 }
1478 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(*export.Export) {})
1479 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1480 t.Errorf("the generation slow readers were served from outlived the activation: %v", err)
1481 }
1482}
1483
1484// Before the first activation the server says nothing is published, and
1485// it answers GET and HEAD alone.
1486func TestNothingPublishedAndMethods(t *testing.T) {
1487 store, err := export.OpenStore(t.TempDir(), nil)
1488 if err != nil {
1489 t.Fatal(err)
1490 }
1491 srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }})
1492 w := httptest.NewRecorder()
1493 srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
1494 if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") {
1495 t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body)
1496 }
1497
1498 h := newHarness(t)
1499 for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} {
1500 w := h.do(method, "/")
1501 if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" {
1502 t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow"))
1503 }
1504 }
1505}
1506
1507// tooLarge checks that GET target answers with the one short page that
1508// says a page is too large.
1509func (h *harness) tooLarge(target string) {
1510 h.t.Helper()
1511 w := h.get(target)
1512 if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) {
1513 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())
1514 }
1515 if n, _ := h.srv.holding(); n != 0 {
1516 h.t.Errorf("GET %s kept %d pieces of the budget", target, n)
1517 }
1518}
1519
1520// A response's body is at most MaxResponse bytes. A page that would pass
1521// the bound answers with the one short page that says it is too large,
1522// and the failure is logged: a knot whose body passes MaxResponse, and,
1523// under a smaller bound, a file, a directory, a page of history and the
1524// plan page. A page within the bound is served on each route.
1525func TestPageTooLarge(t *testing.T) {
1526 h := newHarness(t)
1527 var logged []string
1528 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
1529 files := []file{{"100644", "wide.txt", strings.Repeat("<", 16<<10)}}
1530 for i := range 32 {
1531 files = append(files, file{"100644", fmt.Sprintf("wide/%02d-%s", i, strings.Repeat("n", 1000)), "x\n"})
1532 }
1533 h.commitMain("app: a wide file and a wide directory\n", files...)
1534 var tip, bundle string
1535 for i := range 8 {
1536 tip, bundle = h.commitMain(fmt.Sprintf("%d %s\n", i, strings.Repeat(`"`, maxLogText)))
1537 }
1538 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
1539 p := &e.Projects[0]
1540 p.SourceTip = tip
1541 p.Knots[0].Body = strings.Repeat("a", MaxResponse)
1542 for i := range 100 {
1543 p.Knots = append(p.Knots, export.Knot{ID: fmt.Sprintf("oc-e%06x", i), Type: "outcome", Status: "open",
1544 Active: true, State: "ready", Title: strings.Repeat(`"`, knot.MaxTitle), Created: "2026-10-01", CreatedBy: "operator"})
1545 }
1546 })
1547
1548 h.tooLarge("/app/knots/" + h.f.Export.Projects[0].Knots[0].ID)
1549 h.page("/app/knots/oc-a000002")
1550
1551 h.srv.maxResponse = 32 << 10
1552 at := "/app/source/blob/" + tip + "/"
1553 h.tooLarge(at + "wide.txt")
1554 h.page(at + "docs/guide.md")
1555 at = "/app/source/tree/" + tip + "/"
1556 h.tooLarge(at + "wide/")
1557 h.page(at + "docs/")
1558 h.tooLarge("/app/source/log/" + tip)
1559 h.page("/app/source/log/" + tip + "?skip=8")
1560 h.tooLarge("/")
1561
1562 if len(logged) != 5 {
1563 t.Errorf("%d failures were logged for 5 pages too large: %q", len(logged), logged)
1564 }
1565 for _, l := range logged {
1566 if !strings.Contains(l, "larger than") {
1567 t.Errorf("the server logged %q", l)
1568 }
1569 }
1570 if len(tooLargePage) > 16<<10 {
1571 t.Errorf("the page that says a page is too large is %d bytes", len(tooLargePage))
1572 }
1573}
1574
1575// holding is how many pieces of the budget responses hold, and how many
1576// of those the large budget counts.
1577func (s *Server) holding() (held, large int) {
1578 s.pieces.Lock()
1579 defer s.pieces.Unlock()
1580 return s.held, s.large
1581}
1582
1583// Rendered responses share a budget of MaxBuffered bytes, which each
1584// holds from when it starts rendering until it is written. Responses
1585// larger than SmallPage hold at most MaxLarge of it between them, their
1586// first SmallPage bytes counted. Readers that never read large pages ask
1587// for more than the whole budget, in pages of three sizes: one piece past
1588// SmallPage, 1 MiB, and 4 MiB. Without the first SmallPage bytes counted,
1589// 64 readers of the 1 MiB page would hold all of the budget. Once the
1590// readers' pages hold what fits in MaxLarge, a large page answers 503 at
1591// once, while small pages still render: the plan, a knot and a
1592// directory. The server's heap grows by no more than the budget, and the
1593// budget is whole again once the readers read.
1594func TestSlowReadersShareTheBudget(t *testing.T) {
1595 for _, pieces := range []int{smallPieces + 1, 16, 64} {
1596 t.Run(fmt.Sprintf("%d pieces", pieces), func(t *testing.T) { slowReadersOfPages(t, pieces) })
1597 }
1598}
1599
1600// slowReadersOfPages runs TestSlowReadersShareTheBudget with large pages
1601// of the number of pieces given.
1602func slowReadersOfPages(t *testing.T, pieces int) {
1603 h := newHarness(t)
1604 target := "/app/knots/" + h.f.Export.Projects[0].Knots[0].ID
1605 body := func(at time.Duration, text string) {
1606 h.publish(exporttest.SignedAt.Add(at), nil, func(e *export.Export) { e.Projects[0].Knots[0].Body = text })
1607 }
1608 body(time.Minute, "x")
1609 rest := len(h.page(target)) - 1
1610 body(2*time.Minute, strings.Repeat("a line of a long body\n", (pieces*pieceSize-rest-1024)/22))
1611 size := len(h.page(target))
1612 if got := (size + pieceSize - 1) / pieceSize; got != pieces {
1613 t.Fatalf("the large page takes %d pieces, not %d", got, pieces)
1614 }
1615 fit := largePieces / pieces
1616 n := MaxBuffered/size + 2
1617
1618 ln, err := net.Listen("tcp", "127.0.0.1:0")
1619 if err != nil {
1620 t.Fatal(err)
1621 }
1622 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
1623 sl.stall.Store(true)
1624 srv := &http.Server{Handler: h.srv}
1625 go srv.Serve(sl)
1626 var conns []net.Conn
1627 released := false
1628 defer func() {
1629 if !released {
1630 close(sl.release)
1631 }
1632 for _, c := range conns {
1633 c.Close()
1634 }
1635 srv.Close()
1636 }()
1637
1638 var before runtime.MemStats
1639 runtime.GC()
1640 runtime.ReadMemStats(&before)
1641 // One reader at a time, each stalled before the next asks, so the
1642 // readers that fill the budget are the first fit of them.
1643 for i := range n {
1644 c, err := net.Dial("tcp", ln.Addr().String())
1645 if err != nil {
1646 t.Fatal(err)
1647 }
1648 conns = append(conns, c)
1649 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
1650 select {
1651 case <-sl.stalled:
1652 case <-time.After(10 * time.Second):
1653 t.Fatalf("reader %d of %d was not answered", i+1, n)
1654 }
1655 }
1656 sl.stall.Store(false)
1657 var after runtime.MemStats
1658 runtime.GC()
1659 runtime.ReadMemStats(&after)
1660 if held, large := h.srv.holding(); held != fit*pieces || large != fit*pieces {
1661 t.Errorf("slow readers hold %d pieces, %d of them counted as large; %d pages of %d pieces fit", held, large, fit, pieces)
1662 }
1663 if grew := int64(after.HeapAlloc) - int64(before.HeapAlloc); grew > MaxBuffered+8<<20 {
1664 t.Errorf("%d slow readers of %d bytes each grew the heap by %d bytes, past MaxBuffered", n, size, grew)
1665 }
1666
1667 client := &http.Client{Timeout: 10 * time.Second}
1668 get := func(target string) (int, string) {
1669 t.Helper()
1670 resp, err := client.Get("http://" + ln.Addr().String() + target)
1671 if err != nil {
1672 t.Fatal(err)
1673 }
1674 defer resp.Body.Close()
1675 io.Copy(io.Discard, resp.Body)
1676 return resp.StatusCode, resp.Header.Get("Retry-After")
1677 }
1678 if code, retry := get(target); code != http.StatusServiceUnavailable || retry == "" {
1679 t.Errorf("a page the budget has no room for answered %d, Retry-After %q", code, retry)
1680 }
1681 for _, small := range []string{"/", "/app/knots/oc-a000002", "/app/source/tree/" + h.tip() + "/"} {
1682 if code, _ := get(small); code != http.StatusOK {
1683 t.Errorf("the small page %s answered %d while slow readers hold MaxLarge", small, code)
1684 }
1685 }
1686
1687 close(sl.release)
1688 released = true
1689 codes := map[int]int{}
1690 for _, c := range conns {
1691 c.SetReadDeadline(time.Now().Add(10 * time.Second))
1692 resp, err := http.ReadResponse(bufio.NewReader(c), nil)
1693 if err != nil {
1694 t.Fatal(err)
1695 }
1696 read, err := io.Copy(io.Discard, resp.Body)
1697 resp.Body.Close()
1698 if err != nil || resp.StatusCode == http.StatusOK && read != int64(size) {
1699 t.Errorf("a slow reader read %d bytes of %d: %v", read, size, err)
1700 }
1701 codes[resp.StatusCode]++
1702 }
1703 if codes[http.StatusOK] != fit || codes[http.StatusServiceUnavailable] != n-fit {
1704 t.Errorf("of %d slow readers, %d were served and %d answered 503; %d pages fit the budget",
1705 n, codes[http.StatusOK], codes[http.StatusServiceUnavailable], fit)
1706 }
1707 eventually(t, "the budget is whole again", func() bool { held, _ := h.srv.holding(); return held == 0 })
1708}
1709
1710// A load starts only once a request that waits for it takes a loader
1711// slot. While MaxLoads loads run, a request for a newer generation waits
1712// for a slot, holding no generation, until its time runs out, whatever
1713// its route, or its reader goes away. Neither leaves a load behind.
1714func TestExportLoadWaitsEnd(t *testing.T) {
1715 h := newHarness(t)
1716 var mu sync.Mutex
1717 var logged []string
1718 h.srv.log = func(err error) {
1719 mu.Lock()
1720 defer mu.Unlock()
1721 logged = append(logged, err.Error())
1722 }
1723 loads := map[int64]int{}
1724 hold := make(chan struct{})
1725 h.srv.loading = func(g export.Generation) {
1726 mu.Lock()
1727 loads[g.Sequence]++
1728 mu.Unlock()
1729 <-hold
1730 }
1731 loaded := func(g export.Generation) int {
1732 mu.Lock()
1733 defer mu.Unlock()
1734 return loads[g.Sequence]
1735 }
1736 serve := func(r *http.Request) chan *httptest.ResponseRecorder {
1737 served := make(chan *httptest.ResponseRecorder, 1)
1738 go func() {
1739 w := httptest.NewRecorder()
1740 h.srv.ServeHTTP(w, r)
1741 served <- w
1742 }()
1743 return served
1744 }
1745 expect := func(served chan *httptest.ResponseRecorder, title string) {
1746 t.Helper()
1747 select {
1748 case w := <-served:
1749 if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
1750 t.Errorf("a request answered %d, not with %q", w.Code, title)
1751 }
1752 case <-time.After(10 * time.Second):
1753 t.Fatalf("a request was not answered with %q", title)
1754 }
1755 }
1756
1757 first := h.active()
1758 firstServed := serve(httptest.NewRequest("GET", "/", nil))
1759 eventually(t, "the first generation is read", func() bool { return loaded(first) == 1 })
1760 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1761 secondServed := serve(httptest.NewRequest("GET", "/", nil))
1762 eventually(t, "both loader slots are taken", func() bool { return loaded(second) == 1 })
1763
1764 // A request that runs no git runs out of time waiting, and answers
1765 // 503.
1766 h.srv.timeout = 200 * time.Millisecond
1767 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1768 select {
1769 case w := <-serve(httptest.NewRequest("GET", "/app/knots/oc-a000001", nil)):
1770 if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1771 t.Errorf("a request that waited past its time for a read answered %d", w.Code)
1772 }
1773 case <-time.After(10 * time.Second):
1774 t.Fatal("a request waits for a read past its time of 200ms")
1775 }
1776
1777 // A request whose reader goes away stops waiting, and answers
1778 // nothing.
1779 h.srv.timeout = time.Hour
1780 fourth := h.publish(exporttest.SignedAt.Add(3*time.Minute), nil, renamed("Readers browse the fourth plan"))
1781 ctx, cancel := context.WithCancel(context.Background())
1782 defer cancel()
1783 gone := serve(httptest.NewRequest("GET", "/", nil).WithContext(ctx))
1784 eventually(t, "a request waits for the fourth generation", func() bool { return len(h.srv.loadWaiting) == 3 })
1785 cancel()
1786 select {
1787 case w := <-gone:
1788 if w.Body.Len() != 0 {
1789 t.Errorf("a request whose reader went away answered %d", w.Code)
1790 }
1791 case <-time.After(10 * time.Second):
1792 t.Fatal("a request whose reader went away still waits")
1793 }
1794
1795 h.srv.mu.Lock()
1796 left := len(h.srv.loads)
1797 h.srv.mu.Unlock()
1798 if left != MaxLoads {
1799 t.Errorf("%d loads may be joined; only the %d that run are wanted", left, MaxLoads)
1800 }
1801 h.publish(exporttest.SignedAt.Add(4*time.Minute), nil, renamed("Readers browse the fifth plan"))
1802 for _, g := range []export.Generation{third, fourth} {
1803 if _, err := os.Stat(g.Dir); !os.IsNotExist(err) {
1804 t.Errorf("generation %d outlived an activation after its request gave up: %v", g.Sequence, err)
1805 }
1806 }
1807
1808 // The first two reads end, and their requests are served the newest
1809 // generation.
1810 close(hold)
1811 expect(firstServed, "Readers browse the fifth plan")
1812 expect(secondServed, "Readers browse the fifth plan")
1813 for _, g := range []export.Generation{third, fourth} {
1814 if n := loaded(g); n != 0 {
1815 t.Errorf("generation %d's export was read %d times after every request for it gave up", g.Sequence, n)
1816 }
1817 }
1818 mu.Lock()
1819 defer mu.Unlock()
1820 if len(logged) != 1 || !strings.Contains(logged[0], "deadline exceeded") {
1821 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
1822 }
1823}
1824
1825// A load that reads slowly does not hold the request that waits for it:
1826// the request answers 503 at its deadline. With no request left waiting,
1827// the load stops reading part way through the export, caches nothing, and
1828// gives back its generation, which the next activation deletes. A load
1829// that ends is kept, and the requests after it are served without another
1830// read.
1831func TestSlowLoadEndsWithItsRequests(t *testing.T) {
1832 h := newHarness(t)
1833 h.srv.timeout = 200 * time.Millisecond
1834 var mu sync.Mutex
1835 var logged []string
1836 h.srv.log = func(err error) {
1837 mu.Lock()
1838 defer mu.Unlock()
1839 logged = append(logged, err.Error())
1840 }
1841 var reads atomic.Int32
1842 h.srv.loading = func(export.Generation) { reads.Add(1) }
1843
1844 // The active generation's export.json becomes a pipe the test writes
1845 // a few bytes at a time, as a slow disk would give it: all of it
1846 // takes about 4 seconds, twenty times the request's time.
1847 old := h.active()
1848 data, err := os.ReadFile(old.ExportPath())
1849 if err != nil {
1850 t.Fatal(err)
1851 }
1852 if err := os.Remove(old.ExportPath()); err != nil {
1853 t.Fatal(err)
1854 }
1855 if err := syscall.Mkfifo(old.ExportPath(), 0o600); err != nil {
1856 t.Fatal(err)
1857 }
1858 piece := max(1, len(data)/200)
1859 wrote := make(chan error, 1)
1860 go func() {
1861 f, err := os.OpenFile(old.ExportPath(), os.O_WRONLY, 0)
1862 if err != nil {
1863 wrote <- err
1864 return
1865 }
1866 defer f.Close()
1867 for p := data; len(p) > 0; p = p[min(len(p), piece):] {
1868 if _, err := f.Write(p[:min(len(p), piece)]); err != nil {
1869 wrote <- err
1870 return
1871 }
1872 time.Sleep(20 * time.Millisecond)
1873 }
1874 wrote <- nil
1875 }()
1876
1877 start := time.Now()
1878 if w := h.get("/"); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1879 t.Errorf("a request whose load ran past its time answered %d", w.Code)
1880 }
1881 if waited := time.Since(start); waited > 2*time.Second {
1882 t.Errorf("a request waited %v for a slow load, past its time of 200ms", waited)
1883 }
1884 select {
1885 case err := <-wrote:
1886 if !errors.Is(err, syscall.EPIPE) {
1887 t.Errorf("the load read the whole export after its request gave up: the writer ended with %v", err)
1888 }
1889 case <-time.After(10 * time.Second):
1890 t.Fatal("the load still reads the export")
1891 }
1892 eventually(t, "the load ends", func() bool { return len(h.srv.loaders) == 0 })
1893 h.srv.mu.Lock()
1894 cached, loads := h.srv.cached, len(h.srv.loads)
1895 h.srv.mu.Unlock()
1896 if cached != nil || loads != 0 {
1897 t.Errorf("a load that stopped left a snapshot %v and %d loads", cached != nil, loads)
1898 }
1899 // The store reads the active export.json when it takes an upload.
1900 if err := os.Remove(old.ExportPath()); err != nil {
1901 t.Fatal(err)
1902 }
1903 if err := os.WriteFile(old.ExportPath(), data, 0o644); err != nil {
1904 t.Fatal(err)
1905 }
1906 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1907 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1908 t.Errorf("the generation a stopped load opened outlived an activation: %v", err)
1909 }
1910
1911 h.srv.timeout = requestTimeout
1912 for range 3 {
1913 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the second plan") {
1914 t.Error("a request after the stopped load is not served the new generation")
1915 }
1916 }
1917 if n := reads.Load(); n != 2 {
1918 t.Errorf("exports were read %d times: once in part, and once for the new generation", n)
1919 }
1920 mu.Lock()
1921 defer mu.Unlock()
1922 if len(logged) != 1 || !strings.Contains(logged[0], "export to be read: context deadline exceeded") {
1923 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
1924 }
1925}
1926
1927// openFiles is the number of files the process holds open, and false
1928// where the system does not list them.
1929func openFiles(t *testing.T) (int, bool) {
1930 t.Helper()
1931 entries, err := os.ReadDir("/proc/self/fd")
1932 if err != nil {
1933 return 0, false
1934 }
1935 return len(entries), true
1936}
1937
1938// A flood of requests while a load runs: MaxLoadWaiting of them wait, and
1939// the rest answer 503 at once, unlogged. A waiting request holds no
1940// generation, so the goroutines and files the server holds stay within a
1941// bound however large the flood. Once the load ends, every request that
1942// waited is served from its one read.
1943func TestLoadFlood(t *testing.T) {
1944 h := newHarness(t)
1945 var reads atomic.Int32
1946 reading, hold := make(chan struct{}, 1), make(chan struct{})
1947 h.srv.loading = func(export.Generation) {
1948 reads.Add(1)
1949 reading <- struct{}{}
1950 <-hold
1951 }
1952 get := func(n int) chan *httptest.ResponseRecorder {
1953 served := make(chan *httptest.ResponseRecorder, n)
1954 for range n {
1955 go func() {
1956 w := httptest.NewRecorder()
1957 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
1958 served <- w
1959 }()
1960 }
1961 return served
1962 }
1963
1964 first := get(1)
1965 select {
1966 case <-reading:
1967 case <-time.After(10 * time.Second):
1968 t.Fatal("no load started")
1969 }
1970 goroutines := runtime.NumGoroutine()
1971 files, listed := openFiles(t)
1972
1973 flood := 4 * MaxLoadWaiting
1974 served := get(flood)
1975 refused := flood - (MaxLoadWaiting - 1)
1976 for range refused {
1977 if w := <-served; w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1978 t.Fatalf("a request past MaxLoadWaiting answered %d", w.Code)
1979 }
1980 }
1981 if n := len(h.srv.loadWaiting); n != MaxLoadWaiting {
1982 t.Errorf("%d requests wait for the load, not %d", n, MaxLoadWaiting)
1983 }
1984 const slack = 8
1985 eventually(t, "the refused requests' goroutines end", func() bool {
1986 return runtime.NumGoroutine() <= goroutines+MaxLoadWaiting-1+slack
1987 })
1988 if n, _ := openFiles(t); listed && n > files+slack {
1989 t.Errorf("the flood holds %d files open, %d more than before it", n, n-files)
1990 }
1991
1992 close(hold)
1993 for range MaxLoadWaiting - 1 {
1994 if w := <-served; w.Code != http.StatusOK {
1995 t.Errorf("a request that waited for the load answered %d", w.Code)
1996 }
1997 }
1998 if w := <-first; w.Code != http.StatusOK {
1999 t.Errorf("the request that started the load answered %d", w.Code)
2000 }
2001 if n := reads.Load(); n != 1 {
2002 t.Errorf("the export was read %d times for one generation", n)
2003 }
2004 if n := len(h.srv.loadWaiting); n != 0 {
2005 t.Errorf("%d requests still hold a place among those that wait", n)
2006 }
2007}
2008
2009// A request's time runs from its arrival through its rendering: a request
2010// for a page that runs no git, held past its time before it renders,
2011// answers 503, and the server logs it.
2012func TestRenderingIsWithinTheDeadline(t *testing.T) {
2013 h := newHarness(t)
2014 h.page("/")
2015 h.srv.timeout = 50 * time.Millisecond
2016 var logged []string
2017 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
2018 h.srv.opened = func(export.Generation) { time.Sleep(100 * time.Millisecond) }
2019 if w := h.get("/"); w.Code != http.StatusServiceUnavailable || !bytes.Equal(w.Body.Bytes(), busyPage) {
2020 t.Errorf("a request that ran out of time before it rendered answered %d", w.Code)
2021 }
2022 if len(logged) != 1 || !strings.Contains(logged[0], "rendering plan: context deadline exceeded") {
2023 t.Errorf("the server logged %q", logged)
2024 }
2025 if n, _ := h.srv.holding(); n != 0 {
2026 t.Errorf("a page that stopped rendering kept %d pieces of the budget", n)
2027 }
2028}
2029
2030// A FIFO with a writer that sends no bytes keeps Read blocked until the
2031// request deadline. A FIFO without a writer must not block Open.
2032func TestStalledLoadReleasesGeneration(t *testing.T) {
2033 for _, writer := range []bool{false, true} {
2034 t.Run(fmt.Sprint(writer), func(t *testing.T) {
2035 h := newHarness(t)
2036 h.srv.timeout = 100 * time.Millisecond
2037 h.srv.log = func(error) {}
2038 old := h.active()
2039 data, err := os.ReadFile(old.ExportPath())
2040 if err != nil {
2041 t.Fatal(err)
2042 }
2043 if err := os.Remove(old.ExportPath()); err != nil {
2044 t.Fatal(err)
2045 }
2046 if err := syscall.Mkfifo(old.ExportPath(), 0600); err != nil {
2047 t.Fatal(err)
2048 }
2049 if writer {
2050 f, err := os.OpenFile(old.ExportPath(), os.O_RDWR|syscall.O_NONBLOCK, 0)
2051 if err != nil {
2052 t.Fatal(err)
2053 }
2054 defer f.Close()
2055 if _, err := f.Write([]byte("{")); err != nil {
2056 t.Fatal(err)
2057 }
2058 }
2059 if w := h.get("/"); w.Code != http.StatusServiceUnavailable {
2060 t.Fatalf("status = %d", w.Code)
2061 }
2062 eventually(t, "the stalled worker exits", func() bool { return len(h.srv.loaders) == 0 })
2063 h.srv.mu.Lock()
2064 cached := h.srv.cached
2065 h.srv.mu.Unlock()
2066 if cached != nil {
2067 t.Fatal("stalled load cached a snapshot")
2068 }
2069 if err := os.Remove(old.ExportPath()); err != nil {
2070 t.Fatal(err)
2071 }
2072 if err := os.WriteFile(old.ExportPath(), data, 0644); err != nil {
2073 t.Fatal(err)
2074 }
2075 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan"))
2076 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
2077 t.Fatalf("generation retained: %v", err)
2078 }
2079 h.srv.timeout = requestTimeout
2080 if !strings.Contains(h.page("/app/knots/oc-a000001"), "The second plan") {
2081 t.Fatal("loader slot is not reusable")
2082 }
2083 })
2084 }
2085}
2086
2087// cancelInPhase cancels a real context on the third cancellation check
2088// inside a named processing function. It makes cancellation during CPU
2089// work deterministic without replacing decoding or graph traversal.
2090type cancelInPhase struct {
2091 context.Context
2092 cancel context.CancelFunc
2093 phase string
2094 checks int
2095}
2096
2097func (c *cancelInPhase) Err() error {
2098 var pcs [32]uintptr
2099 n := runtime.Callers(2, pcs[:])
2100 frames := runtime.CallersFrames(pcs[:n])
2101 for {
2102 frame, more := frames.Next()
2103 if strings.HasSuffix(frame.Function, c.phase) {
2104 c.checks++
2105 if c.checks == 3 {
2106 c.cancel()
2107 }
2108 break
2109 }
2110 if !more {
2111 break
2112 }
2113 }
2114 return c.Context.Err()
2115}
2116
2117func TestProcessingCancellationReleasesGeneration(t *testing.T) {
2118 for _, phase := range []string{".decodeValue", ".(*Export).ValidateContext", ".(*index).planPage", ".(*index).paths", ".(*index).milestones"} {
2119 t.Run(phase, func(t *testing.T) {
2120 h := newHarness(t)
2121 old := h.active()
2122 base, cancel := context.WithCancel(context.Background())
2123 defer cancel()
2124 ctx := &cancelInPhase{Context: base, cancel: cancel, phase: phase}
2125 l := &load{done: make(chan struct{}), cancel: cancel}
2126 h.srv.loads[l] = struct{}{}
2127 h.srv.loaders <- struct{}{}
2128 finished := make(chan struct{})
2129 go func() { h.srv.run(ctx, l); close(finished) }()
2130 select {
2131 case <-finished:
2132 case <-time.After(2 * time.Second):
2133 t.Fatal("processing did not stop")
2134 }
2135 if ctx.checks < 3 {
2136 t.Fatalf("phase was not reached: %d checks", ctx.checks)
2137 }
2138 if !errors.Is(l.err, context.Canceled) {
2139 t.Fatalf("load error = %v", l.err)
2140 }
2141 if h.srv.cached != nil || len(h.srv.loaders) != 0 || len(h.srv.loads) != 0 {
2142 t.Fatal("cancelled processing retained load state")
2143 }
2144 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan"))
2145 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
2146 t.Fatalf("generation retained: %v", err)
2147 }
2148 if !strings.Contains(h.page("/app/knots/oc-a000001"), "The second plan") {
2149 t.Fatal("loader slot is not reusable")
2150 }
2151 })
2152 }
2153}