gunk-dev/the-valley

server_test.go

source876e6ddf614dmain's published tip history
73.1 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 "waits on oc-a000002",
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// unpublishedText is what of the hidden project site the fixture's
265// references hold: its name and its knots' IDs. No page shows any of it.
266var unpublishedText = []string{"site:", "oc-b000001", "oc-b000002", "lands in site", ">site<", "valley:site"}
267
268// A knot's page shows its body and comments, and marks the edited
269// comment. A reference into a hidden project is shown as unpublished,
270// with nothing of its text, and a missing knot of a public project is
271// named as missing.
272func TestKnotPage(t *testing.T) {
273 h := newHarness(t)
274 page := h.page("/app/knots/oc-a000002")
275 for _, want := range []string{
276 "Each milestone is listed with its progress.",
277 "Start with the milestones that have open children.",
278 "Claimed; the change is ready for approval.",
279 `<span class="chip quiet">edited</span><span>2026-10-25 10:30 UTC by agent</span>`,
280 `<a href="/app/knots/oc-a000001">Readers browse the app&#39;s plan</a>`,
281 } {
282 if !strings.Contains(page, want) {
283 t.Errorf("the knot's page does not show %q", want)
284 }
285 }
286 if n := strings.Count(page, ">edited<"); n != 1 {
287 t.Errorf("%d comments are marked edited; one was edited", n)
288 }
289
290 page = h.page("/app/knots/oc-a000003")
291 if !strings.Contains(page, `<a href="/app/knots/oc-a000002">The plan page lists milestones</a>`) {
292 t.Error("the local blocker is not linked")
293 }
294 for _, want := range []string{
295 `<span class="nochild"></span><span class="t"><span class="muted">a knot in an unpublished project</span></span>`,
296 "<dt>Lands in</dt><dd>an unpublished project</dd>",
297 } {
298 if !strings.Contains(page, want) {
299 t.Errorf("the knot's page does not show %q", want)
300 }
301 }
302 page += h.page("/app/knots/bd-a000004")
303 if !strings.Contains(page, "<dt>Lands in</dt><dd>a knot in an unpublished project</dd>") {
304 t.Error("a target in the hidden project is not shown as unpublished")
305 }
306 for _, unwanted := range append([]string{"/site/knots/", "/site/source/"}, unpublishedText...) {
307 if strings.Contains(page, unwanted) {
308 t.Errorf("the knot's page shows %q", unwanted)
309 }
310 }
311 if w := h.get("/app/knots/oc-fffffff"); w.Code != http.StatusNotFound {
312 t.Errorf("a missing knot answered %d", w.Code)
313 }
314
315 // A knot of a public project the graph does not hold, and a local
316 // knot that is not there, are named as missing. A change of the
317 // hidden project is not named.
318 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
319 for i := range e.Projects[0].Knots {
320 if k := &e.Projects[0].Knots[i]; k.ID == "oc-a000003" {
321 k.BlockedBy = append(k.BlockedBy, "app:oc-fffffff", "oc-eeeeeee")
322 k.Edges = append(k.Edges, export.Edge{Field: "blocked_by", Ref: "app:oc-fffffff", Project: "app", ID: "oc-fffffff", State: export.EdgeDangling})
323 k.Changes = append(k.Changes, "valley:site/kmnopqrstuvwxyzkmnopqrstuvwxyzkm", "valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm")
324 }
325 }
326 })
327 page = h.page("/app/knots/oc-a000003")
328 for _, want := range []string{
329 `<span class="mono">app:oc-fffffff</span> <span class="muted">not found in its graph</span>`,
330 `<span class="mono">oc-eeeeeee</span> <span class="muted">not found</span>`,
331 `<li class="mono">a change in an unpublished project</li>`,
332 `<li class="mono">valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm</li>`,
333 } {
334 if !strings.Contains(page, want) {
335 t.Errorf("the knot's page does not show %q", want)
336 }
337 }
338 for _, unwanted := range unpublishedText {
339 if strings.Contains(page, unwanted) {
340 t.Errorf("the knot's page shows %q", unwanted)
341 }
342 }
343}
344
345// A project the export does not hold as public answers every route
346// exactly as a project that does not exist, even when its repository is
347// in the generation's directory.
348func TestHiddenProjectAnswersLikeMissing(t *testing.T) {
349 h := newHarness(t)
350 g := h.active()
351 if err := os.CopyFS(filepath.Join(g.Dir, "repos", "site.git"), os.DirFS(h.f.Repos["site"])); err != nil {
352 t.Fatal(err)
353 }
354 siteTip := git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef)
355 notFound := h.get("/app/knots/oc-fffffff")
356 for _, route := range []string{
357 "/%s",
358 "/%s/",
359 "/%s/knots/oc-b000001",
360 "/%s/source",
361 "/%s/source/",
362 "/%s/source/tree/" + siteTip + "/",
363 "/%s/source/blob/" + siteTip + "/README.md",
364 "/%s/source/log/" + siteTip,
365 "/%s/source/tree/" + siteTip + "/no/such/path/",
366 "/%s/source/anything",
367 } {
368 hidden, missing := h.get(fmt.Sprintf(route, "site")), h.get(fmt.Sprintf(route, "nosuch"))
369 if hidden.Code != http.StatusNotFound || missing.Code != http.StatusNotFound {
370 t.Errorf("%s answered %d hidden and %d missing", route, hidden.Code, missing.Code)
371 }
372 if fmt.Sprint(hidden.Header()) != fmt.Sprint(missing.Header()) {
373 t.Errorf("%s answered with other headers hidden than missing:\n%v\n%v", route, hidden.Header(), missing.Header())
374 }
375 if !bytes.Equal(hidden.Body.Bytes(), missing.Body.Bytes()) || !bytes.Equal(hidden.Body.Bytes(), notFound.Body.Bytes()) {
376 t.Errorf("%s answered with another page hidden than missing", route)
377 }
378 }
379}
380
381// A project's name may be any word the server's routes use: source,
382// knots, or web-export, the receiver's first segment. Each such project
383// is served on every route, and /<project>/ redirects to its tree. The
384// server's own paths, under /-/, are never a project's.
385func TestProjectNamesBesideTheServersPaths(t *testing.T) {
386 for _, name := range []string{"source", "knots", "web-export"} {
387 t.Run(name, func(t *testing.T) {
388 h := newHarness(t)
389 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{name: h.f.Bundles["app"]},
390 func(e *export.Export) { e.Projects[0].Name = name })
391 tip := h.tip()
392 tree := "/" + name + "/source/tree/" + tip + "/"
393 if plan := h.page("/"); !strings.Contains(plan, `href="/`+name+`/knots/oc-a000002"`) {
394 t.Errorf("the plan page does not link %s's knots", name)
395 }
396 for _, target := range []string{
397 "/" + name + "/knots/oc-a000002",
398 tree,
399 "/" + name + "/source/blob/" + tip + "/docs/guide.md",
400 "/" + name + "/source/log/" + tip,
401 } {
402 h.page(target)
403 }
404 for _, target := range []string{"/" + name + "/", "/" + name, "/" + name + "/source/"} {
405 if w := h.get(target); w.Code != http.StatusFound || w.Header().Get("Location") != tree {
406 t.Errorf("GET %s answered %d to %q, not a redirect to %s", target, w.Code, w.Header().Get("Location"), tree)
407 }
408 }
409 for _, target := range []string{
410 "/-", "/-/", "/-/" + name + "/", "/-/knots/oc-a000002", "/-/source/tree/" + tip + "/",
411 "/-/" + name + "/source/tree/" + tip + "/", "/app/", "/site/", "/site",
412 } {
413 if w := h.get(target); w.Code != http.StatusNotFound {
414 t.Errorf("GET %s answered %d, not 404", target, w.Code)
415 }
416 }
417 })
418 }
419}
420
421// A source route serves a commit only when main's published tip reaches
422// it, and refuses every other object ID or name with the one 404.
423func TestUnreachableCommitIsRefused(t *testing.T) {
424 h := newHarness(t)
425 repo, _ := h.active().Repo("app")
426 tip := h.tip()
427 tree := git(t, repo, nil, "rev-parse", tip+"^{tree}")
428 readme := git(t, repo, nil, "rev-parse", tip+":README.md")
429 side := git(t, repo, nil, "commit-tree", tree, "-p", tip, "-m", "a commit main does not reach")
430 parent := git(t, repo, nil, "rev-parse", tip+"~2")
431 notFound := h.get("/app/knots/oc-fffffff").Body.String()
432
433 for _, commit := range []string{side, tree, readme, tip[:12], "main", "HEAD", strings.Repeat("0", 40), tip + "~1"} {
434 for _, route := range []string{"/app/source/tree/%s/", "/app/source/blob/%s/README.md", "/app/source/log/%s"} {
435 target := fmt.Sprintf(route, commit)
436 w := h.get(target)
437 if w.Code != http.StatusNotFound || w.Body.String() != notFound {
438 t.Errorf("GET %s answered %d, not the one 404", target, w.Code)
439 }
440 }
441 }
442
443 // A commit the tip reaches is served, as that commit had it.
444 page := h.page("/app/source/blob/" + parent + "/README.md")
445 if !strings.Contains(page, "A synthetic project for the web UI&#39;s tests.") || strings.Contains(page, "readme") {
446 t.Errorf("the first README is not served as the first commit had it:\n%s", page)
447 }
448}
449
450// The source browser lists a directory and its README, shows a file and
451// main's log, and every source link names its project, a full commit and
452// a path.
453func TestSourceBrowser(t *testing.T) {
454 h := newHarness(t)
455 tip := h.tip()
456
457 for _, path := range []string{"/app/source", "/app/source/"} {
458 w := h.get(path)
459 if w.Code != http.StatusFound || w.Header().Get("Location") != "/app/source/tree/"+tip+"/" {
460 t.Fatalf("the project's source answered %d to %q", w.Code, w.Header().Get("Location"))
461 }
462 }
463
464 root := h.page("/app/source/tree/" + tip + "/")
465 docs, src, readme := strings.Index(root, ">docs/<"), strings.Index(root, ">src/<"), strings.Index(root, ">README.md<")
466 if docs < 0 || src < 0 || readme < 0 || readme < src || src < docs {
467 t.Errorf("the root does not list docs/ and src/ before README.md:\n%s", root)
468 }
469 if !strings.Contains(root, `<pre class="text"># app`) {
470 t.Error("the root does not show its README")
471 }
472 if dir := h.page("/app/source/tree/" + tip + "/docs/"); !strings.Contains(dir, ">guide.md<") {
473 t.Error("docs/ does not list guide.md")
474 }
475 file := h.page("/app/source/blob/" + tip + "/docs/guide.md")
476 if !strings.Contains(file, `<tr id="L1"><td class="ln"><a href="#L1">1</a></td><td class="src"># Guide</td></tr>`) {
477 t.Errorf("the file is not shown line by line:\n%s", file)
478 }
479 log := h.page("/app/source/log/" + tip)
480 first, last := strings.Index(log, "docs: a guide, and the README names it"), strings.Index(log, "app: the first README")
481 if first < 0 || last < first {
482 t.Errorf("the log does not list main's commits newest first:\n%s", log)
483 }
484
485 links := regexp.MustCompile(`href="(/[^"]*/source/[^"]*)"`)
486 named := regexp.MustCompile(`^/app/source/(tree|blob|log)/[0-9a-f]{40}(/|$)`)
487 for _, page := range []string{root, file, log} {
488 for _, m := range links.FindAllStringSubmatch(page, -1) {
489 if !named.MatchString(m[1]) {
490 t.Errorf("the link %s names no commit", m[1])
491 }
492 }
493 }
494
495 for _, target := range []string{
496 "/app/source/tree/" + tip + "/README.md/",
497 "/app/source/blob/" + tip + "/docs",
498 "/app/source/blob/" + tip + "/docs/guide.md/",
499 "/app/source/blob/" + tip + "/docs/../README.md",
500 "/app/source/blob/" + tip + "/docs%2Fguide.md",
501 "/app/source/tree/" + tip + "//",
502 "/app/source/log/" + tip + "?skip=-1",
503 } {
504 if w := h.get(target); w.Code != http.StatusNotFound {
505 t.Errorf("GET %s answered %d", target, w.Code)
506 }
507 }
508}
509
510// file is one file a test commits: its mode, path and content.
511type file struct{ mode, path, content string }
512
513// commitMain writes a commit onto the fixture's app main, with message,
514// that holds the files given beside what main holds. It returns the new
515// tip and a bundle of it. Each content is written once, however many
516// files hold it.
517func (h *harness) commitMain(message string, files ...file) (tip, bundle string) {
518 t := h.t
519 t.Helper()
520 repo := h.f.Repos["app"]
521 var b bytes.Buffer
522 data := func(s string) { fmt.Fprintf(&b, "data %d\n%s\n", len(s), s) }
523 marks := map[string]int{}
524 for _, f := range files {
525 if _, ok := marks[f.content]; !ok {
526 marks[f.content] = len(marks) + 1
527 fmt.Fprintf(&b, "blob\nmark :%d\n", marks[f.content])
528 data(f.content)
529 }
530 }
531 who := "Example Author <author@example.org> 1791190800 +0000"
532 fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who)
533 data(message)
534 fmt.Fprintf(&b, "from %s\n", git(t, repo, nil, "rev-parse", export.MainRef))
535 for _, f := range files {
536 fmt.Fprintf(&b, "M %s :%d %s\n", f.mode, marks[f.content], f.path)
537 }
538 git(t, repo, b.Bytes(), "fast-import", "--quiet")
539 tip = git(t, repo, nil, "rev-parse", export.MainRef)
540 bundle = filepath.Join(t.TempDir(), "app.bundle")
541 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
542 return tip, bundle
543}
544
545// publishMain activates a generation whose app main is tip, carried by
546// bundle.
547func (h *harness) publishMain(at time.Time, tip, bundle string) {
548 h.t.Helper()
549 h.publish(at, map[string]string{"app": bundle}, func(e *export.Export) { e.Projects[0].SourceTip = tip })
550}
551
552// hostileMain writes a commit onto the fixture's app main that holds a
553// file of HTML, a file larger than a page shows, a binary file, a file
554// whose name is HTML, and a symbolic link out of the repository. It
555// returns the new tip and a bundle of it.
556func (h *harness) hostileMain() (tip, bundle string) {
557 return h.commitMain("hostile: <script>alert(\"subject\")</script>\n",
558 file{"100644", "page.html", "<html><script>alert(\"file\")</script><img src=x onerror=alert(2)></html>\n"},
559 file{"100644", "big.txt", strings.Repeat("big\n", (MaxFile/4)+1)},
560 file{"100644", "binary.bin", "\x7fELF\x00\x01\x02<script>alert(\"binary\")</script>"},
561 file{"100644", "<img src=x onerror=alert(3)>.txt", "named\n"},
562 file{"120000", "link", "../../etc/passwd"},
563 )
564}
565
566// HTML, scripts, large files and binary files from a repository or the
567// plan render inert: escaped as text, or not shown.
568func TestHostileContentRendersInert(t *testing.T) {
569 h := newHarness(t)
570 tip, bundle := h.hostileMain()
571 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
572 e.Projects[0].SourceTip = tip
573 })
574
575 inert := func(target, page string, wants ...string) {
576 t.Helper()
577 // Escaped, a tag is text; only a tag the page did not escape, or
578 // an attribute it let a value break out into, is active.
579 for _, active := range []string{"<script", "<img", `" onerror`, "\x00"} {
580 if strings.Contains(page, active) {
581 t.Errorf("GET %s holds %q", target, active)
582 }
583 }
584 for _, want := range wants {
585 if !strings.Contains(page, want) {
586 t.Errorf("GET %s does not show %q", target, want)
587 }
588 }
589 }
590 at := "/app/source/tree/" + tip + "/"
591 inert(at, h.page(at),
592 `&lt;script&gt;alert(&#34;readme&#34;)&lt;/script&gt;`,
593 `&lt;img src=x onerror=alert(3)&gt;.txt`,
594 `href="/app/source/blob/`+tip+`/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"`)
595 at = "/app/source/blob/" + tip + "/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"
596 inert(at, h.page(at), ">named<")
597 at = "/app/source/blob/" + tip + "/page.html"
598 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;`)
599 at = "/app/source/blob/" + tip + "/big.txt"
600 page := h.page(at)
601 inert(at, page, "This file is 1.0 MiB, larger than the 1.0 MiB a page shows.")
602 if len(page) > 64<<10 {
603 t.Errorf("the large file's page is %d bytes", len(page))
604 }
605 at = "/app/source/blob/" + tip + "/binary.bin"
606 inert(at, h.page(at), "This file is binary, 39 bytes, and is not shown.")
607 at = "/app/source/blob/" + tip + "/link"
608 inert(at, h.page(at), "A symbolic link to ../../etc/passwd. It is not followed.")
609 at = "/app/source/log/" + tip
610 inert(at, h.page(at), "hostile: &lt;script&gt;alert(&#34;subject&#34;)&lt;/script&gt;")
611
612 at = "/app/knots/bd-a000004"
613 inert(at, h.page(at),
614 `A README holding &lt;script&gt;alert(&#34;knot&#34;)&lt;/script&gt; must show as text.`,
615 `Also &lt;img src=x onerror=alert(1)&gt; in a comment.`)
616}
617
618// A directory larger than a page reads is listed in part, and a commit
619// message larger than a page reads ends its page of history early. git
620// is stopped once its listing passes MaxRead, and nothing past a record's
621// bound is kept.
622func TestOversizedTreeAndHistory(t *testing.T) {
623 h := newHarness(t)
624 // Each entry of huge/ takes 308 bytes of git ls-tree's output, so
625 // 15,000 of them pass MaxRead at about entry 13,600.
626 longest := "!" + strings.Repeat("l", 4095)
627 files := []file{{"100644", "huge/" + longest, "x\n"}}
628 name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) }
629 for i := range 15_000 {
630 files = append(files, file{"100644", "huge/" + name(i), "x\n"})
631 }
632 if n := 15_000 * (6 + 1 + 4 + 1 + 40 + 1 + 7 + 1 + 246 + 1); n <= MaxRead {
633 t.Fatalf("the listing of huge/ is %d bytes, within MaxRead", n)
634 }
635 h.commitMain("app: a directory larger than a page reads\n", files...)
636 h.commitMain("long: " + strings.Repeat("a long subject ", (100<<10)/15) + "\n")
637 tip, bundle := h.commitMain("longer: " + strings.Repeat("a subject past the bound ", (5<<20)/25) + "\n")
638 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
639
640 at := "/app/source/tree/" + tip + "/huge/"
641 page := h.page(at)
642 if !strings.Contains(page, "This directory is larger than a page reads, so only part of it is listed.") {
643 t.Error("huge/ is not marked as listed in part")
644 }
645 if n := strings.Count(page, `<tr><td class="name">`); n != MaxEntries {
646 t.Errorf("huge/ lists %d entries, not %d", n, MaxEntries)
647 }
648 if !strings.Contains(page, `">`+longest+`</a>`) {
649 t.Error("the entry with the longest name git accepts is not listed whole")
650 }
651 if len(page) > 1<<20 {
652 t.Errorf("huge/'s page is %d bytes", len(page))
653 }
654 if w := h.get("/app/source/blob/" + tip + "/huge/" + name(0)); w.Code != http.StatusOK {
655 t.Errorf("an entry read before MaxRead answered %d", w.Code)
656 }
657 if w := h.get("/app/source/blob/" + tip + "/huge/" + name(14_999)); w.Code != http.StatusNotFound {
658 t.Errorf("an entry past MaxRead answered %d", w.Code)
659 }
660
661 at = "/app/source/log/" + tip
662 page = h.page(at)
663 if !strings.Contains(page, "This page ends early: its commits are larger than a page reads.") {
664 t.Error("the page of history holding a 5 MiB message does not end early")
665 }
666 if n := strings.Count(page, `<tr><td class="name">`); n != 1 {
667 t.Errorf("the page that ends early lists %d commits, not the one it cut", n)
668 }
669 if m := regexp.MustCompile(`<td>(longer: a subject past the bound[^<]*)…</td>`).FindStringSubmatch(page); m == nil || len(m[1]) > maxLogText {
670 t.Error("the cut commit's subject is not shown cut to maxLogText")
671 }
672 if !strings.Contains(page, `href="/app/source/log/`+tip+`?skip=1"`) {
673 t.Error("the page that ends early does not link the commits after the one it cut")
674 }
675 page = h.page(at + "?skip=1")
676 if strings.Contains(page, "ends early") || !strings.Contains(page, "long: a long subject") || !strings.Contains(page, "app: the first README") {
677 t.Errorf("the next page of history is not whole:\n%s", page)
678 }
679 if strings.Contains(page, strings.Repeat("a long subject ", (maxLogText/15)+1)) {
680 t.Error("a subject longer than a page shows is not cut")
681 }
682 for _, p := range []string{at, at + "?skip=1"} {
683 if n := len(h.page(p)); n > 64<<10 {
684 t.Errorf("GET %s is %d bytes", p, n)
685 }
686 }
687}
688
689// The directories along a path share one budget of MaxRead bytes of git
690// ls-tree's output. Each of big/ and big/zz/ lists about 3 MB before
691// the entry the path names next, within MaxRead alone, so the directory
692// big/zz/ is served. A path through both, to big/zz/zz/f, passes the
693// budget and answers 404. The directory's own listing has a budget of
694// its own.
695func TestResolveSharesOneBudget(t *testing.T) {
696 h := newHarness(t)
697 name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) }
698 var files []file
699 for i := range 10_000 {
700 files = append(files, file{"100644", "big/" + name(i), "x\n"}, file{"100644", "big/zz/" + name(i), "x\n"})
701 }
702 files = append(files, file{"100644", "big/zz/zz/f", "the file\n"})
703 if each := 6 + 1 + 4 + 1 + 40 + 1 + 246 + 1; 10_000*each > MaxRead || 2*10_000*each <= MaxRead {
704 t.Fatalf("the listings take %d bytes each, not between half MaxRead and MaxRead", 10_000*each)
705 }
706 tip, bundle := h.commitMain("app: two large directories, one in the other\n", files...)
707 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
708
709 h.page("/app/source/tree/" + tip + "/big/zz/")
710 h.page("/app/source/blob/" + tip + "/big/zz/" + name(0))
711 for _, target := range []string{"/app/source/tree/" + tip + "/big/zz/zz/", "/app/source/blob/" + tip + "/big/zz/zz/f"} {
712 if w := h.get(target); w.Code != http.StatusNotFound {
713 t.Errorf("GET %s, through %d bytes of listings, answered %d", target, 2*10_000*300, w.Code)
714 }
715 }
716}
717
718// A page of history skips at most MaxSkip commits. The page at MaxSkip
719// links the commits older than it as the history that ends at its last
720// commit, less that commit, and that page is served.
721func TestLogSkipIsBounded(t *testing.T) {
722 h := newHarness(t)
723 repo := h.f.Repos["app"]
724 var b bytes.Buffer
725 who := "Example Author <author@example.org> 1791190800 +0000"
726 n := MaxSkip + LogPage + 10
727 for i := range n {
728 fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who)
729 msg := fmt.Sprintf("commit %d\n", i)
730 fmt.Fprintf(&b, "data %d\n%s\n", len(msg), msg)
731 if i == 0 {
732 fmt.Fprintf(&b, "from %s\n", git(t, repo, nil, "rev-parse", export.MainRef))
733 }
734 }
735 git(t, repo, b.Bytes(), "fast-import", "--quiet")
736 tip := git(t, repo, nil, "rev-parse", export.MainRef)
737 bundle := filepath.Join(t.TempDir(), "app.bundle")
738 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
739 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
740
741 at := "/app/source/log/" + tip
742 if page := h.page(at + fmt.Sprintf("?skip=%d", MaxSkip-LogPage)); !strings.Contains(page, fmt.Sprintf(`href="%s?skip=%d"`, at, MaxSkip)) {
743 t.Errorf("the page before MaxSkip does not link the page at it")
744 }
745 page := h.page(at + fmt.Sprintf("?skip=%d", MaxSkip))
746 // The page at MaxSkip shows commits n-1-MaxSkip down to
747 // n-MaxSkip-LogPage, the last of them, counting from the oldest new
748 // commit as 0.
749 last := git(t, repo, nil, "rev-parse", fmt.Sprintf("%s~%d", tip, MaxSkip+LogPage-1))
750 older := "/app/source/log/" + last + "?skip=1"
751 if !strings.Contains(page, `href="`+older+`"`) {
752 t.Errorf("the page at MaxSkip does not link its older commits as the history of %s", last)
753 }
754 page = h.page(older)
755 if !strings.Contains(page, fmt.Sprintf("commit %d<", n-MaxSkip-LogPage-1)) || !strings.Contains(page, "app: the first README") {
756 t.Errorf("the history past MaxSkip is not served:\n%s", page)
757 }
758 if strings.Contains(page, fmt.Sprintf("commit %d<", n-MaxSkip-LogPage)) {
759 t.Error("the history past MaxSkip shows the commit it starts after")
760 }
761 if w := h.get(at + fmt.Sprintf("?skip=%d", MaxSkip+1)); w.Code != http.StatusNotFound {
762 t.Errorf("a page skipping past MaxSkip answered %d", w.Code)
763 }
764}
765
766// A source request's git commands have a bound of their own, far within
767// the request's time: a git that does not finish is stopped once it
768// passes, and the request answers 503 and gives back its git slot. The
769// failure is logged.
770func TestSourceGitHasItsOwnBound(t *testing.T) {
771 h := newHarness(t)
772 real, err := exec.LookPath(export.GitProgram)
773 if err != nil {
774 t.Fatal(err)
775 }
776 if real, err = filepath.Abs(real); err != nil {
777 t.Fatal(err)
778 }
779 slow := filepath.Join(t.TempDir(), "git")
780 script := "#!/bin/sh\nfor a; do [ \"$a\" = ls-tree ] && exec sleep 60; done\nexec '" + real + "' \"$@\"\n"
781 if err := os.WriteFile(slow, []byte(script), 0o755); err != nil {
782 t.Fatal(err)
783 }
784 program := export.GitProgram
785 export.GitProgram = slow
786 t.Cleanup(func() { export.GitProgram = program })
787 var logged []error
788 var mu sync.Mutex
789 h.srv.log = func(err error) { mu.Lock(); logged = append(logged, err); mu.Unlock() }
790 h.srv.gitTime = 300 * time.Millisecond
791
792 start := time.Now()
793 w := h.get("/app/source/tree/" + h.tip() + "/")
794 if took := time.Since(start); w.Code != http.StatusServiceUnavailable || took > 5*time.Second {
795 t.Errorf("a source request whose git does not finish answered %d after %v", w.Code, took)
796 }
797 if len(h.srv.slots) != 0 {
798 t.Errorf("the request holds %d git slots once it answered", len(h.srv.slots))
799 }
800 mu.Lock()
801 defer mu.Unlock()
802 if len(logged) != 1 || !strings.Contains(logged[0].Error(), "the request's git ran past 300ms") {
803 t.Errorf("the server logged %v", logged)
804 }
805 if w := h.get("/app/knots/oc-a000002"); w.Code != http.StatusOK {
806 t.Errorf("a knot answered %d", w.Code)
807 }
808}
809
810// A SHA-256 project's commits are served by their 64 hex digits alone.
811// The first 40 of them, which git would read as an abbreviation, answer
812// 404 on every source route, so each page has one address.
813func TestSHA256CommitIDs(t *testing.T) {
814 h := newHarness(t)
815 repo := filepath.Join(t.TempDir(), "app.git")
816 git(t, repo, nil, "init", "--quiet", "--bare", "--template=", "--initial-branch=main", "--object-format=sha256")
817 readme := "# app\n\nA SHA-256 repository.\n"
818 who := "Example Author <author@example.org> 1791190800 +0000"
819 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",
820 who, who, len(readme), readme)
821 git(t, repo, []byte(stream), "fast-import", "--quiet")
822 tip := git(t, repo, nil, "rev-parse", export.MainRef)
823 if len(tip) != 64 {
824 t.Fatalf("the tip is %q", tip)
825 }
826 bundle := filepath.Join(t.TempDir(), "app.bundle")
827 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
828 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
829
830 for _, route := range []string{"/app/source/tree/%s/", "/app/source/blob/%s/README.md", "/app/source/log/%s"} {
831 if page := h.page(fmt.Sprintf(route, tip)); !strings.Contains(page, tip[:12]) {
832 t.Errorf("%s does not name the commit", fmt.Sprintf(route, tip))
833 }
834 if w := h.get(fmt.Sprintf(route, tip[:40])); w.Code != http.StatusNotFound {
835 t.Errorf("%s answered %d", fmt.Sprintf(route, tip[:40]), w.Code)
836 }
837 }
838 if w := h.get("/app/source/"); w.Header().Get("Location") != "/app/source/tree/"+tip+"/" {
839 t.Errorf("/app/source/ redirects to %q", w.Header().Get("Location"))
840 }
841}
842
843// A file of exactly MaxFile bytes of newlines is shown to MaxLines lines,
844// and its page says where it stops. A README longer than a page shows is
845// shown in part.
846func TestLongFileIsShownInPart(t *testing.T) {
847 h := newHarness(t)
848 tip, bundle := h.commitMain("app: long files\n",
849 file{"100644", "newlines.txt", strings.Repeat("\n", MaxFile)},
850 file{"100644", "long/README.md", strings.Repeat("a line of the README\n", 2*MaxLines)},
851 file{"100644", "wide.txt", strings.Repeat("<", MaxFile)},
852 )
853 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
854
855 page := h.page("/app/source/blob/" + tip + "/newlines.txt")
856 last := fmt.Sprintf(`id="L%d"`, MaxLines)
857 if !strings.Contains(page, last) || strings.Contains(page, fmt.Sprintf(`id="L%d"`, MaxLines+1)) {
858 t.Errorf("the file of newlines is not shown to line %d", MaxLines)
859 }
860 if want := fmt.Sprintf("The page stops at line %d of %d.", MaxLines, MaxFile); !strings.Contains(page, want) {
861 t.Errorf("the page does not say %q", want)
862 }
863 if len(page) > MaxShown {
864 t.Errorf("the page of a file of newlines is %d bytes, past MaxShown", len(page))
865 }
866
867 // One line of MaxFile characters that each escape to four bytes is
868 // cut where MaxShown is reached.
869 page = h.page("/app/source/blob/" + tip + "/wide.txt")
870 if !strings.Contains(page, "The page stops at line 1 of 1.") || len(page) > MaxShown+64<<10 {
871 t.Errorf("the page of one wide line is %d bytes", len(page))
872 }
873
874 page = h.page("/app/source/tree/" + tip + "/long/")
875 if !strings.Contains(page, "This README is longer than a page shows, and only its start is shown.") {
876 t.Error("the long README is not marked as shown in part")
877 }
878 if n := strings.Count(page, "a line of the README"); n != MaxLines {
879 t.Errorf("the long README shows %d lines, not %d", n, MaxLines)
880 }
881}
882
883// A chain of knots as deep as the graph's knot limit allows renders its
884// milestone to MaxPlanDepth levels, counts every knot under it, and
885// names MaxPlanDepth parents in the deepest knot's trail. The plan page's
886// structure is built once for the generation. Siblings that block one
887// another in a cycle share the last stage of their path.
888func TestDeepPlan(t *testing.T) {
889 h := newHarness(t)
890 var chain []string
891 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
892 p := &e.Projects[0]
893 for i := range knot.MaxKnots - len(p.Knots) - 3 {
894 id := fmt.Sprintf("oc-c%06x", i)
895 k := export.Knot{ID: id, Type: "outcome", Status: "open", Active: true, State: "ready",
896 Title: fmt.Sprintf("Level %d of the chain", i), Created: "2026-10-01", CreatedBy: "operator"}
897 if i == 0 {
898 p.Roots = append(p.Roots, id)
899 } else {
900 k.Parent = chain[i-1]
901 p.Knots[len(p.Knots)-1].Children = []string{id}
902 }
903 chain = append(chain, id)
904 p.Knots = append(p.Knots, k)
905 }
906 // Under the first link, a path whose two last siblings wait on
907 // each other.
908 free, a, b := "oc-d000001", "oc-d000002", "oc-d000003"
909 for _, k := range []export.Knot{
910 {ID: free, BlockedBy: []string{}},
911 {ID: a, BlockedBy: []string{free, b}},
912 {ID: b, BlockedBy: []string{a}},
913 } {
914 k.Type, k.Status, k.State, k.Title, k.Parent = "outcome", "open", "blocked", "Sibling "+k.ID, chain[0]
915 p.Knots = append(p.Knots, k)
916 }
917 for i := range p.Knots {
918 if p.Knots[i].ID == chain[0] {
919 p.Knots[i].Children = append(p.Knots[i].Children, free, a, b)
920 }
921 }
922 })
923
924 page := h.page("/")
925 if want := fmt.Sprintf("%d of %d done", 0, len(chain)-1+3); !strings.Contains(page, want) {
926 t.Errorf("the chain's milestone does not count every knot under it as %q", want)
927 }
928 if !strings.Contains(page, `href="/app/knots/`+chain[MaxPlanDepth]+`"`) || strings.Contains(page, `href="/app/knots/`+chain[MaxPlanDepth+1]+`"`) {
929 t.Errorf("the chain's tree is not shown to %d levels", MaxPlanDepth)
930 }
931 if n := strings.Count(page, ">more on its page<"); n != 1 {
932 t.Errorf("%d rows say there is more on their page; the chain's deepest shown row does", n)
933 }
934 if len(page) > 256<<10 {
935 t.Errorf("the plan page is %d bytes", len(page))
936 }
937 paths := section(t, page, `id="paths-h"`, `id="ms-h"`)
938 stage := regexp.MustCompile(`<span class="stage-num">(\d+)</span><ul class="plain">(.*?)</ul>`)
939 var stages []string
940 for _, m := range stage.FindAllStringSubmatch(paths, -1) {
941 if strings.Contains(m[2], "Sibling") {
942 var ids []string
943 for _, id := range regexp.MustCompile(`"mono muted">(oc-d00000\d)<`).FindAllStringSubmatch(m[2], -1) {
944 ids = append(ids, id[1])
945 }
946 stages = append(stages, m[1]+":"+strings.Join(ids, ","))
947 }
948 }
949 if got := strings.Join(stages, " "); got != "1:oc-d000001 2:oc-d000002,oc-d000003" {
950 t.Errorf("the siblings' path has stages %q", got)
951 }
952
953 h.srv.mu.Lock()
954 plan := h.srv.cached.idx.plan
955 h.srv.mu.Unlock()
956 h.page("/")
957 h.srv.mu.Lock()
958 again := h.srv.cached.idx.plan
959 h.srv.mu.Unlock()
960 if plan != again {
961 t.Error("the plan page's structure was built again for the same generation")
962 }
963
964 deepest := chain[len(chain)-1]
965 page = h.page("/app/knots/" + deepest)
966 trail := section(t, page, `<nav class="trail"`, `</nav>`)
967 if n := strings.Count(trail, `<a href="/app/knots/`); n != MaxPlanDepth || !strings.Contains(trail, "<span>…</span>") {
968 t.Errorf("the deepest knot's trail names %d parents, or does not mark those above them", n)
969 }
970 if !strings.Contains(trail, chain[len(chain)-2]) || strings.Contains(trail, `"/app/knots/`+chain[len(chain)-2-MaxPlanDepth]+`"`) {
971 t.Error("the trail does not name the nearest parents alone")
972 }
973}
974
975// Every response carries the strict policy, and the policy admits the
976// page's one inline stylesheet and one inline script by their hashes and
977// nothing from another origin.
978func TestEveryResponseCarriesTheCSP(t *testing.T) {
979 h := newHarness(t)
980 for _, c := range []struct{ method, target string }{
981 {"GET", "/"},
982 {"GET", "/app/knots/oc-a000002"},
983 {"GET", "/app/source/"},
984 {"GET", "/app/source/tree/" + h.tip() + "/"},
985 {"GET", "/app/source/blob/" + h.tip() + "/README.md"},
986 {"GET", "/no/such/page"},
987 {"POST", "/"},
988 {"HEAD", "/"},
989 } {
990 w := h.do(c.method, c.target)
991 got := w.Header().Get("Content-Security-Policy")
992 if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" {
993 t.Errorf("%s %s answered with policy %q", c.method, c.target, got)
994 }
995 }
996 for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} {
997 if !strings.Contains(csp, directive) {
998 t.Errorf("the policy lacks %s", directive)
999 }
1000 }
1001 for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} {
1002 if strings.Contains(csp, loose) {
1003 t.Errorf("the policy holds %q", loose)
1004 }
1005 }
1006
1007 page := h.page("/")
1008 inline := func(tag string) string {
1009 t.Helper()
1010 m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1)
1011 if len(m) != 1 || strings.Count(page, "<"+tag) != 1 {
1012 t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag)
1013 }
1014 sum := sha256.Sum256([]byte(m[0][1]))
1015 return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
1016 }
1017 if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") {
1018 t.Errorf("the policy does not admit the page's script, %s", hash)
1019 }
1020 if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") {
1021 t.Errorf("the policy does not admit the page's stylesheet, %s", hash)
1022 }
1023 for _, external := range []string{"<link", " src=", "@import", "url("} {
1024 if strings.Contains(page, external) {
1025 t.Errorf("the plan page holds %q", external)
1026 }
1027 }
1028}
1029
1030// A request serves everything from the generation it opened, though
1031// another activates while it runs, and that generation outlives the
1032// activation until the request releases it.
1033func TestARequestKeepsItsGeneration(t *testing.T) {
1034 h := newHarness(t)
1035 paused, resume := make(chan export.Generation), make(chan struct{})
1036 var once sync.Once
1037 h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) }
1038 served := make(chan *httptest.ResponseRecorder)
1039 go func() {
1040 w := httptest.NewRecorder()
1041 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/knots/oc-a000001", nil))
1042 served <- w
1043 }()
1044 old := <-paused
1045
1046 next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1047 if next.Sequence == old.Sequence {
1048 t.Fatal("the publish did not activate a new generation")
1049 }
1050 if _, err := os.Stat(old.Dir); err != nil {
1051 t.Fatalf("the generation a request holds was deleted: %v", err)
1052 }
1053 close(resume)
1054 w := <-served
1055 if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app&#39;s plan") || strings.Contains(body, "second plan") {
1056 t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body)
1057 }
1058 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the second plan") {
1059 t.Error("the next request does not serve the new generation")
1060 }
1061
1062 // Released, the old generation goes with the next activation.
1063 h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1064 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1065 t.Errorf("the released generation is still on disk: %v", err)
1066 }
1067}
1068
1069// eventually waits up to ten seconds for cond to hold.
1070func eventually(t *testing.T, what string, cond func() bool) {
1071 t.Helper()
1072 for deadline := time.Now().Add(10 * time.Second); !cond(); time.Sleep(time.Millisecond) {
1073 if time.Now().After(deadline) {
1074 t.Fatalf("timed out waiting until %s", what)
1075 }
1076 }
1077}
1078
1079// renamed changes the title of the fixture's first knot.
1080func renamed(title string) func(*export.Export) {
1081 return func(e *export.Export) { e.Projects[0].Knots[0].Title = title }
1082}
1083
1084// Requests that wait for a generation together read its export once.
1085// While it is read, a newer generation is read on its own, and at most
1086// MaxLoads exports are read at once. A request whose load ends after a
1087// newer generation was activated waits for that one, so every request is
1088// served the generation active when its snapshot is ready, and an older
1089// read that finishes last does not displace the newest snapshot.
1090func TestExportLoadsCoalesce(t *testing.T) {
1091 h := newHarness(t)
1092 var mu sync.Mutex
1093 loads := map[int64]int{}
1094 holds := map[int64]chan struct{}{}
1095 hold := func(g export.Generation) chan struct{} {
1096 mu.Lock()
1097 defer mu.Unlock()
1098 if holds[g.Sequence] == nil {
1099 holds[g.Sequence] = make(chan struct{})
1100 }
1101 return holds[g.Sequence]
1102 }
1103 h.srv.loading = func(g export.Generation) {
1104 mu.Lock()
1105 loads[g.Sequence]++
1106 mu.Unlock()
1107 <-hold(g)
1108 }
1109 loaded := func(g export.Generation) int {
1110 mu.Lock()
1111 defer mu.Unlock()
1112 return loads[g.Sequence]
1113 }
1114 var opens atomic.Int32
1115 h.srv.opened = func(export.Generation) { opens.Add(1) }
1116 get := func(n int) chan *httptest.ResponseRecorder {
1117 served := make(chan *httptest.ResponseRecorder, n)
1118 for range n {
1119 go func() {
1120 w := httptest.NewRecorder()
1121 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/knots/oc-a000001", nil))
1122 served <- w
1123 }()
1124 }
1125 return served
1126 }
1127 expect := func(served chan *httptest.ResponseRecorder, n int, title string) {
1128 t.Helper()
1129 for range n {
1130 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
1131 t.Errorf("a request answered %d, not with %q", w.Code, title)
1132 }
1133 }
1134 }
1135 waiting := func(n int) func() bool { return func() bool { return len(h.srv.loadWaiting) == n } }
1136
1137 first := h.active()
1138 firstServed := get(10)
1139 eventually(t, "ten requests wait for the first generation's read", func() bool {
1140 return loaded(first) == 1 && len(h.srv.loadWaiting) == 10
1141 })
1142 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1143 secondServed := get(1)
1144 eventually(t, "the second generation is read", func() bool { return loaded(second) == 1 })
1145
1146 // Both loaders are taken, so the third generation waits for one.
1147 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1148 thirdServed := get(1)
1149 eventually(t, "a request waits for the third generation", waiting(12))
1150 time.Sleep(20 * time.Millisecond)
1151 if n := loaded(third); n != 0 {
1152 t.Errorf("a third export was read while %d were", MaxLoads)
1153 }
1154 if n := opens.Load(); n != 0 {
1155 t.Errorf("%d requests opened a generation while they waited for its read", n)
1156 }
1157
1158 // The second read ends, and its request finds the third generation
1159 // active, and waits for that read with the third's request.
1160 close(hold(second))
1161 eventually(t, "the third generation is read", func() bool { return loaded(third) == 1 })
1162 close(hold(third))
1163 expect(secondServed, 1, "Readers browse the third plan")
1164 expect(thirdServed, 1, "Readers browse the third plan")
1165 close(hold(first))
1166 expect(firstServed, 10, "Readers browse the third plan")
1167
1168 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the third plan") {
1169 t.Error("the first generation's read displaced the third's")
1170 }
1171 for _, g := range []export.Generation{first, second, third} {
1172 if n := loaded(g); n != 1 {
1173 t.Errorf("generation %d's export was read %d times", g.Sequence, n)
1174 }
1175 }
1176}
1177
1178// Source requests past MaxGit wait, MaxWaiting of them, and one more
1179// answers 503 at once. A waiting request holds no generation, so an
1180// activation while the server is saturated deletes the old generation,
1181// and every waiting request serves the new one. A request's time runs
1182// from its arrival, so one that waits past it answers 503.
1183func TestSourceAdmission(t *testing.T) {
1184 h := newHarness(t)
1185 var admitted atomic.Int32
1186 release := make(chan struct{})
1187 h.srv.admitted = func() {
1188 admitted.Add(1)
1189 <-release
1190 }
1191 target := "/app/source/tree/" + h.tip() + "/"
1192 get := func(n int) chan *httptest.ResponseRecorder {
1193 served := make(chan *httptest.ResponseRecorder, n)
1194 for range n {
1195 go func() {
1196 w := httptest.NewRecorder()
1197 h.srv.ServeHTTP(w, httptest.NewRequest("GET", target, nil))
1198 served <- w
1199 }()
1200 }
1201 return served
1202 }
1203
1204 old := h.active()
1205 served := get(MaxGit + MaxWaiting)
1206 eventually(t, "every slot is taken and MaxWaiting requests wait", func() bool {
1207 return admitted.Load() == MaxGit && len(h.srv.waiting) == MaxWaiting
1208 })
1209 if w := h.get(target); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1210 t.Errorf("a source request past MaxWaiting answered %d, Retry-After %q", w.Code, w.Header().Get("Retry-After"))
1211 }
1212 h.page("/") // a page that runs no git is served still
1213
1214 tip, bundle := h.commitMain("app: a commit while the server is saturated\n", file{"100644", "saturated.txt", "saturated\n"})
1215 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1216 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1217 t.Errorf("a generation no request had opened outlived the activation: %v", err)
1218 }
1219 close(release)
1220 for range MaxGit + MaxWaiting {
1221 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "/app/source/tree/"+tip+"/") {
1222 t.Errorf("a waiting request answered %d, not from the new generation", w.Code)
1223 }
1224 }
1225
1226 // A request that waits past its time answers 503. Those that held
1227 // the slots meanwhile ran out of time too.
1228 h.srv.timeout = 200 * time.Millisecond
1229 h.srv.log = func(error) {}
1230 admitted.Store(0)
1231 release = make(chan struct{})
1232 held := get(MaxGit)
1233 eventually(t, "every slot is taken", func() bool { return admitted.Load() == MaxGit })
1234 start := time.Now()
1235 if w := h.get(target); w.Code != http.StatusServiceUnavailable {
1236 t.Errorf("a request that waited past its time answered %d", w.Code)
1237 }
1238 if waited := time.Since(start); waited > 5*time.Second {
1239 t.Errorf("a request waited %v past its time of 200ms", waited)
1240 }
1241 close(release)
1242 for range MaxGit {
1243 if w := <-held; w.Code != http.StatusServiceUnavailable {
1244 t.Errorf("a request that ran out of time answered %d", w.Code)
1245 }
1246 }
1247}
1248
1249// stallingListener accepts connections whose writes stall until release
1250// is closed, while stall is set. Each sends on stalled the first time one
1251// of its writes stalls.
1252type stallingListener struct {
1253 net.Listener
1254 stall atomic.Bool
1255 release chan struct{}
1256 stalled chan struct{}
1257}
1258
1259func (l *stallingListener) Accept() (net.Conn, error) {
1260 c, err := l.Listener.Accept()
1261 if err != nil || !l.stall.Load() {
1262 return c, err
1263 }
1264 return &stallingConn{Conn: c, l: l}, nil
1265}
1266
1267type stallingConn struct {
1268 net.Conn
1269 l *stallingListener
1270 once sync.Once
1271}
1272
1273func (c *stallingConn) Write(p []byte) (int, error) {
1274 c.once.Do(func() { c.l.stalled <- struct{}{} })
1275 <-c.l.release
1276 return c.Conn.Write(p)
1277}
1278
1279// Readers that never read their responses hold no git slot and no
1280// generation: more of them than MaxGit and MaxWaiting together are
1281// stalled writing, and a new reader is still served, and an activation
1282// deletes the generation they were served from.
1283func TestSlowReadersHoldNothing(t *testing.T) {
1284 h := newHarness(t)
1285 ln, err := net.Listen("tcp", "127.0.0.1:0")
1286 if err != nil {
1287 t.Fatal(err)
1288 }
1289 n := MaxGit + MaxWaiting + 4
1290 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
1291 sl.stall.Store(true)
1292 srv := &http.Server{Handler: h.srv}
1293 go srv.Serve(sl)
1294 var conns []net.Conn
1295 defer func() {
1296 close(sl.release)
1297 for _, c := range conns {
1298 c.Close()
1299 }
1300 srv.Close()
1301 }()
1302
1303 old := h.active()
1304 target := "/app/source/blob/" + h.tip() + "/docs/guide.md"
1305 for range n {
1306 c, err := net.Dial("tcp", ln.Addr().String())
1307 if err != nil {
1308 t.Fatal(err)
1309 }
1310 conns = append(conns, c)
1311 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
1312 }
1313 for i := range n {
1314 select {
1315 case <-sl.stalled:
1316 case <-time.After(10 * time.Second):
1317 t.Fatalf("%d of %d slow readers' responses were written; the rest wait", i, n)
1318 }
1319 }
1320 sl.stall.Store(false)
1321 if len(h.srv.slots) != 0 || len(h.srv.waiting) != 0 {
1322 t.Errorf("slow readers hold %d git slots, and %d requests wait", len(h.srv.slots), len(h.srv.waiting))
1323 }
1324
1325 client := &http.Client{Timeout: 10 * time.Second}
1326 resp, err := client.Get("http://" + ln.Addr().String() + target)
1327 if err != nil {
1328 t.Fatal(err)
1329 }
1330 resp.Body.Close()
1331 if resp.StatusCode != http.StatusOK {
1332 t.Errorf("a new reader answered %d while slow readers stall", resp.StatusCode)
1333 }
1334 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(*export.Export) {})
1335 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1336 t.Errorf("the generation slow readers were served from outlived the activation: %v", err)
1337 }
1338}
1339
1340// Before the first activation the server says nothing is published, and
1341// it answers GET and HEAD alone.
1342func TestNothingPublishedAndMethods(t *testing.T) {
1343 store, err := export.OpenStore(t.TempDir(), nil)
1344 if err != nil {
1345 t.Fatal(err)
1346 }
1347 srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }})
1348 w := httptest.NewRecorder()
1349 srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
1350 if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") {
1351 t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body)
1352 }
1353
1354 h := newHarness(t)
1355 for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} {
1356 w := h.do(method, "/")
1357 if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" {
1358 t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow"))
1359 }
1360 }
1361}
1362
1363// tooLarge checks that GET target answers with the one short page that
1364// says a page is too large.
1365func (h *harness) tooLarge(target string) {
1366 h.t.Helper()
1367 w := h.get(target)
1368 if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) {
1369 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())
1370 }
1371 if n := len(h.srv.budget); n != 0 {
1372 h.t.Errorf("GET %s kept %d pieces of the budget", target, n)
1373 }
1374}
1375
1376// A response's body is at most MaxResponse bytes. A page that would pass
1377// the bound answers with the one short page that says it is too large,
1378// and the failure is logged: a knot whose body passes MaxResponse, and,
1379// under a smaller bound, a file, a directory, a page of history and the
1380// plan page. A page within the bound is served on each route.
1381func TestPageTooLarge(t *testing.T) {
1382 h := newHarness(t)
1383 var logged []string
1384 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
1385 files := []file{{"100644", "wide.txt", strings.Repeat("<", 16<<10)}}
1386 for i := range 32 {
1387 files = append(files, file{"100644", fmt.Sprintf("wide/%02d-%s", i, strings.Repeat("n", 1000)), "x\n"})
1388 }
1389 h.commitMain("app: a wide file and a wide directory\n", files...)
1390 var tip, bundle string
1391 for i := range 8 {
1392 tip, bundle = h.commitMain(fmt.Sprintf("%d %s\n", i, strings.Repeat(`"`, maxLogText)))
1393 }
1394 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
1395 p := &e.Projects[0]
1396 p.SourceTip = tip
1397 p.Knots[0].Body = strings.Repeat("a", MaxResponse)
1398 for i := range 100 {
1399 p.Knots = append(p.Knots, export.Knot{ID: fmt.Sprintf("oc-e%06x", i), Type: "outcome", Status: "open",
1400 Active: true, State: "ready", Title: strings.Repeat(`"`, knot.MaxTitle), Created: "2026-10-01", CreatedBy: "operator"})
1401 }
1402 })
1403
1404 h.tooLarge("/app/knots/" + h.f.Export.Projects[0].Knots[0].ID)
1405 h.page("/app/knots/oc-a000002")
1406
1407 h.srv.maxResponse = 32 << 10
1408 at := "/app/source/blob/" + tip + "/"
1409 h.tooLarge(at + "wide.txt")
1410 h.page(at + "docs/guide.md")
1411 at = "/app/source/tree/" + tip + "/"
1412 h.tooLarge(at + "wide/")
1413 h.page(at + "docs/")
1414 h.tooLarge("/app/source/log/" + tip)
1415 h.page("/app/source/log/" + tip + "?skip=8")
1416 h.tooLarge("/")
1417
1418 if len(logged) != 5 {
1419 t.Errorf("%d failures were logged for 5 pages too large: %q", len(logged), logged)
1420 }
1421 for _, l := range logged {
1422 if !strings.Contains(l, "larger than") {
1423 t.Errorf("the server logged %q", l)
1424 }
1425 }
1426 if len(tooLargePage) > 16<<10 {
1427 t.Errorf("the page that says a page is too large is %d bytes", len(tooLargePage))
1428 }
1429}
1430
1431// Rendered responses share a budget of MaxBuffered bytes, which each
1432// holds from when it starts rendering until it is written. What a
1433// response renders past its first SmallPage bytes takes only MaxLarge of
1434// it. Readers that never read large pages ask for twice the budget in
1435// all, with pages sized so that, but for MaxLarge, sixteen of them would
1436// hold all of it. Once their pages hold MaxLarge, a large page answers
1437// 503 at once, while small pages still render: the plan, a knot and a
1438// directory. The server's heap grows by no more than the budget, and the
1439// budget is whole again once the readers read.
1440func TestSlowReadersShareTheBudget(t *testing.T) {
1441 h := newHarness(t)
1442 target := "/app/knots/" + h.f.Export.Projects[0].Knots[0].ID
1443 body := func(at time.Duration, text string) {
1444 h.publish(exporttest.SignedAt.Add(at), nil, func(e *export.Export) { e.Projects[0].Knots[0].Body = text })
1445 }
1446 body(time.Minute, "x")
1447 rest := len(h.page(target)) - 1
1448 pieces := 64
1449 body(2*time.Minute, strings.Repeat("a line of a long body\n", (pieces*pieceSize-rest-1024)/22))
1450 size := len(h.page(target))
1451 if got := (size + pieceSize - 1) / pieceSize; got != pieces || cap(h.srv.budget)%pieces != 0 {
1452 t.Fatalf("the large page takes %d pieces, not %d, which divide the budget", got, pieces)
1453 }
1454 fit := cap(h.srv.large) / (pieces - smallPieces)
1455 n := 2*MaxBuffered/size + 1
1456
1457 ln, err := net.Listen("tcp", "127.0.0.1:0")
1458 if err != nil {
1459 t.Fatal(err)
1460 }
1461 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
1462 sl.stall.Store(true)
1463 srv := &http.Server{Handler: h.srv}
1464 go srv.Serve(sl)
1465 var conns []net.Conn
1466 released := false
1467 defer func() {
1468 if !released {
1469 close(sl.release)
1470 }
1471 for _, c := range conns {
1472 c.Close()
1473 }
1474 srv.Close()
1475 }()
1476
1477 var before runtime.MemStats
1478 runtime.GC()
1479 runtime.ReadMemStats(&before)
1480 // One reader at a time, each stalled before the next asks, so the
1481 // readers that fill the budget are the first fit of them.
1482 for i := range n {
1483 c, err := net.Dial("tcp", ln.Addr().String())
1484 if err != nil {
1485 t.Fatal(err)
1486 }
1487 conns = append(conns, c)
1488 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
1489 select {
1490 case <-sl.stalled:
1491 case <-time.After(10 * time.Second):
1492 t.Fatalf("reader %d of %d was not answered", i+1, n)
1493 }
1494 }
1495 sl.stall.Store(false)
1496 var after runtime.MemStats
1497 runtime.GC()
1498 runtime.ReadMemStats(&after)
1499 if held, large := len(h.srv.budget), len(h.srv.large); held != fit*pieces || large != fit*(pieces-smallPieces) {
1500 t.Errorf("slow readers hold %d pieces, %d of them large; %d pages of %d pieces fit", held, large, fit, pieces)
1501 }
1502 if grew := int64(after.HeapAlloc) - int64(before.HeapAlloc); grew > MaxBuffered+8<<20 {
1503 t.Errorf("%d slow readers of %d bytes each grew the heap by %d bytes, past MaxBuffered", n, size, grew)
1504 }
1505
1506 client := &http.Client{Timeout: 10 * time.Second}
1507 get := func(target string) (int, string) {
1508 t.Helper()
1509 resp, err := client.Get("http://" + ln.Addr().String() + target)
1510 if err != nil {
1511 t.Fatal(err)
1512 }
1513 defer resp.Body.Close()
1514 io.Copy(io.Discard, resp.Body)
1515 return resp.StatusCode, resp.Header.Get("Retry-After")
1516 }
1517 if code, retry := get(target); code != http.StatusServiceUnavailable || retry == "" {
1518 t.Errorf("a page the budget has no room for answered %d, Retry-After %q", code, retry)
1519 }
1520 for _, small := range []string{"/", "/app/knots/oc-a000002", "/app/source/tree/" + h.tip() + "/"} {
1521 if code, _ := get(small); code != http.StatusOK {
1522 t.Errorf("the small page %s answered %d while slow readers hold MaxLarge", small, code)
1523 }
1524 }
1525
1526 close(sl.release)
1527 released = true
1528 codes := map[int]int{}
1529 for _, c := range conns {
1530 c.SetReadDeadline(time.Now().Add(10 * time.Second))
1531 resp, err := http.ReadResponse(bufio.NewReader(c), nil)
1532 if err != nil {
1533 t.Fatal(err)
1534 }
1535 read, err := io.Copy(io.Discard, resp.Body)
1536 resp.Body.Close()
1537 if err != nil || resp.StatusCode == http.StatusOK && read != int64(size) {
1538 t.Errorf("a slow reader read %d bytes of %d: %v", read, size, err)
1539 }
1540 codes[resp.StatusCode]++
1541 }
1542 if codes[http.StatusOK] != fit || codes[http.StatusServiceUnavailable] != n-fit {
1543 t.Errorf("of %d slow readers, %d were served and %d answered 503; %d pages fit the budget",
1544 n, codes[http.StatusOK], codes[http.StatusServiceUnavailable], fit)
1545 }
1546 eventually(t, "the budget is whole again", func() bool { return len(h.srv.budget) == 0 })
1547}
1548
1549// A load starts only once a request that waits for it takes a loader
1550// slot. While MaxLoads loads run, a request for a newer generation waits
1551// for a slot, holding no generation, until its time runs out, whatever
1552// its route, or its reader goes away. Neither leaves a load behind.
1553func TestExportLoadWaitsEnd(t *testing.T) {
1554 h := newHarness(t)
1555 var mu sync.Mutex
1556 var logged []string
1557 h.srv.log = func(err error) {
1558 mu.Lock()
1559 defer mu.Unlock()
1560 logged = append(logged, err.Error())
1561 }
1562 loads := map[int64]int{}
1563 hold := make(chan struct{})
1564 h.srv.loading = func(g export.Generation) {
1565 mu.Lock()
1566 loads[g.Sequence]++
1567 mu.Unlock()
1568 <-hold
1569 }
1570 loaded := func(g export.Generation) int {
1571 mu.Lock()
1572 defer mu.Unlock()
1573 return loads[g.Sequence]
1574 }
1575 serve := func(r *http.Request) chan *httptest.ResponseRecorder {
1576 served := make(chan *httptest.ResponseRecorder, 1)
1577 go func() {
1578 w := httptest.NewRecorder()
1579 h.srv.ServeHTTP(w, r)
1580 served <- w
1581 }()
1582 return served
1583 }
1584 expect := func(served chan *httptest.ResponseRecorder, title string) {
1585 t.Helper()
1586 select {
1587 case w := <-served:
1588 if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
1589 t.Errorf("a request answered %d, not with %q", w.Code, title)
1590 }
1591 case <-time.After(10 * time.Second):
1592 t.Fatalf("a request was not answered with %q", title)
1593 }
1594 }
1595
1596 first := h.active()
1597 firstServed := serve(httptest.NewRequest("GET", "/", nil))
1598 eventually(t, "the first generation is read", func() bool { return loaded(first) == 1 })
1599 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1600 secondServed := serve(httptest.NewRequest("GET", "/", nil))
1601 eventually(t, "both loader slots are taken", func() bool { return loaded(second) == 1 })
1602
1603 // A request that runs no git runs out of time waiting, and answers
1604 // 503.
1605 h.srv.timeout = 200 * time.Millisecond
1606 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1607 select {
1608 case w := <-serve(httptest.NewRequest("GET", "/app/knots/oc-a000001", nil)):
1609 if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1610 t.Errorf("a request that waited past its time for a read answered %d", w.Code)
1611 }
1612 case <-time.After(10 * time.Second):
1613 t.Fatal("a request waits for a read past its time of 200ms")
1614 }
1615
1616 // A request whose reader goes away stops waiting, and answers
1617 // nothing.
1618 h.srv.timeout = time.Hour
1619 fourth := h.publish(exporttest.SignedAt.Add(3*time.Minute), nil, renamed("Readers browse the fourth plan"))
1620 ctx, cancel := context.WithCancel(context.Background())
1621 defer cancel()
1622 gone := serve(httptest.NewRequest("GET", "/", nil).WithContext(ctx))
1623 eventually(t, "a request waits for the fourth generation", func() bool { return len(h.srv.loadWaiting) == 3 })
1624 cancel()
1625 select {
1626 case w := <-gone:
1627 if w.Body.Len() != 0 {
1628 t.Errorf("a request whose reader went away answered %d", w.Code)
1629 }
1630 case <-time.After(10 * time.Second):
1631 t.Fatal("a request whose reader went away still waits")
1632 }
1633
1634 h.srv.mu.Lock()
1635 left := len(h.srv.loads)
1636 h.srv.mu.Unlock()
1637 if left != MaxLoads {
1638 t.Errorf("%d loads may be joined; only the %d that run are wanted", left, MaxLoads)
1639 }
1640 h.publish(exporttest.SignedAt.Add(4*time.Minute), nil, renamed("Readers browse the fifth plan"))
1641 for _, g := range []export.Generation{third, fourth} {
1642 if _, err := os.Stat(g.Dir); !os.IsNotExist(err) {
1643 t.Errorf("generation %d outlived an activation after its request gave up: %v", g.Sequence, err)
1644 }
1645 }
1646
1647 // The first two reads end, and their requests are served the newest
1648 // generation.
1649 close(hold)
1650 expect(firstServed, "Readers browse the fifth plan")
1651 expect(secondServed, "Readers browse the fifth plan")
1652 for _, g := range []export.Generation{third, fourth} {
1653 if n := loaded(g); n != 0 {
1654 t.Errorf("generation %d's export was read %d times after every request for it gave up", g.Sequence, n)
1655 }
1656 }
1657 mu.Lock()
1658 defer mu.Unlock()
1659 if len(logged) != 1 || !strings.Contains(logged[0], "deadline exceeded") {
1660 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
1661 }
1662}
1663
1664// A load that reads slowly does not hold the request that waits for it:
1665// the request answers 503 at its deadline. With no request left waiting,
1666// the load stops reading part way through the export, caches nothing, and
1667// gives back its generation, which the next activation deletes. A load
1668// that ends is kept, and the requests after it are served without another
1669// read.
1670func TestSlowLoadEndsWithItsRequests(t *testing.T) {
1671 h := newHarness(t)
1672 h.srv.timeout = 200 * time.Millisecond
1673 var mu sync.Mutex
1674 var logged []string
1675 h.srv.log = func(err error) {
1676 mu.Lock()
1677 defer mu.Unlock()
1678 logged = append(logged, err.Error())
1679 }
1680 var reads atomic.Int32
1681 h.srv.loading = func(export.Generation) { reads.Add(1) }
1682
1683 // The active generation's export.json becomes a pipe the test writes
1684 // a few bytes at a time, as a slow disk would give it: all of it
1685 // takes about 4 seconds, twenty times the request's time.
1686 old := h.active()
1687 data, err := os.ReadFile(old.ExportPath())
1688 if err != nil {
1689 t.Fatal(err)
1690 }
1691 if err := os.Remove(old.ExportPath()); err != nil {
1692 t.Fatal(err)
1693 }
1694 if err := syscall.Mkfifo(old.ExportPath(), 0o600); err != nil {
1695 t.Fatal(err)
1696 }
1697 piece := max(1, len(data)/200)
1698 wrote := make(chan error, 1)
1699 go func() {
1700 f, err := os.OpenFile(old.ExportPath(), os.O_WRONLY, 0)
1701 if err != nil {
1702 wrote <- err
1703 return
1704 }
1705 defer f.Close()
1706 for p := data; len(p) > 0; p = p[min(len(p), piece):] {
1707 if _, err := f.Write(p[:min(len(p), piece)]); err != nil {
1708 wrote <- err
1709 return
1710 }
1711 time.Sleep(20 * time.Millisecond)
1712 }
1713 wrote <- nil
1714 }()
1715
1716 start := time.Now()
1717 if w := h.get("/"); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1718 t.Errorf("a request whose load ran past its time answered %d", w.Code)
1719 }
1720 if waited := time.Since(start); waited > 2*time.Second {
1721 t.Errorf("a request waited %v for a slow load, past its time of 200ms", waited)
1722 }
1723 select {
1724 case err := <-wrote:
1725 if !errors.Is(err, syscall.EPIPE) {
1726 t.Errorf("the load read the whole export after its request gave up: the writer ended with %v", err)
1727 }
1728 case <-time.After(10 * time.Second):
1729 t.Fatal("the load still reads the export")
1730 }
1731 eventually(t, "the load ends", func() bool { return len(h.srv.loaders) == 0 })
1732 h.srv.mu.Lock()
1733 cached, loads := h.srv.cached, len(h.srv.loads)
1734 h.srv.mu.Unlock()
1735 if cached != nil || loads != 0 {
1736 t.Errorf("a load that stopped left a snapshot %v and %d loads", cached != nil, loads)
1737 }
1738 // The store reads the active export.json when it takes an upload.
1739 if err := os.Remove(old.ExportPath()); err != nil {
1740 t.Fatal(err)
1741 }
1742 if err := os.WriteFile(old.ExportPath(), data, 0o644); err != nil {
1743 t.Fatal(err)
1744 }
1745 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1746 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1747 t.Errorf("the generation a stopped load opened outlived an activation: %v", err)
1748 }
1749
1750 h.srv.timeout = requestTimeout
1751 for range 3 {
1752 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the second plan") {
1753 t.Error("a request after the stopped load is not served the new generation")
1754 }
1755 }
1756 if n := reads.Load(); n != 2 {
1757 t.Errorf("exports were read %d times: once in part, and once for the new generation", n)
1758 }
1759 mu.Lock()
1760 defer mu.Unlock()
1761 if len(logged) != 1 || !strings.Contains(logged[0], "export to be read: context deadline exceeded") {
1762 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
1763 }
1764}
1765
1766// openFiles is the number of files the process holds open, and false
1767// where the system does not list them.
1768func openFiles(t *testing.T) (int, bool) {
1769 t.Helper()
1770 entries, err := os.ReadDir("/proc/self/fd")
1771 if err != nil {
1772 return 0, false
1773 }
1774 return len(entries), true
1775}
1776
1777// A flood of requests while a load runs: MaxLoadWaiting of them wait, and
1778// the rest answer 503 at once, unlogged. A waiting request holds no
1779// generation, so the goroutines and files the server holds stay within a
1780// bound however large the flood. Once the load ends, every request that
1781// waited is served from its one read.
1782func TestLoadFlood(t *testing.T) {
1783 h := newHarness(t)
1784 var reads atomic.Int32
1785 reading, hold := make(chan struct{}, 1), make(chan struct{})
1786 h.srv.loading = func(export.Generation) {
1787 reads.Add(1)
1788 reading <- struct{}{}
1789 <-hold
1790 }
1791 get := func(n int) chan *httptest.ResponseRecorder {
1792 served := make(chan *httptest.ResponseRecorder, n)
1793 for range n {
1794 go func() {
1795 w := httptest.NewRecorder()
1796 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
1797 served <- w
1798 }()
1799 }
1800 return served
1801 }
1802
1803 first := get(1)
1804 select {
1805 case <-reading:
1806 case <-time.After(10 * time.Second):
1807 t.Fatal("no load started")
1808 }
1809 goroutines := runtime.NumGoroutine()
1810 files, listed := openFiles(t)
1811
1812 flood := 4 * MaxLoadWaiting
1813 served := get(flood)
1814 refused := flood - (MaxLoadWaiting - 1)
1815 for range refused {
1816 if w := <-served; w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1817 t.Fatalf("a request past MaxLoadWaiting answered %d", w.Code)
1818 }
1819 }
1820 if n := len(h.srv.loadWaiting); n != MaxLoadWaiting {
1821 t.Errorf("%d requests wait for the load, not %d", n, MaxLoadWaiting)
1822 }
1823 const slack = 8
1824 eventually(t, "the refused requests' goroutines end", func() bool {
1825 return runtime.NumGoroutine() <= goroutines+MaxLoadWaiting-1+slack
1826 })
1827 if n, _ := openFiles(t); listed && n > files+slack {
1828 t.Errorf("the flood holds %d files open, %d more than before it", n, n-files)
1829 }
1830
1831 close(hold)
1832 for range MaxLoadWaiting - 1 {
1833 if w := <-served; w.Code != http.StatusOK {
1834 t.Errorf("a request that waited for the load answered %d", w.Code)
1835 }
1836 }
1837 if w := <-first; w.Code != http.StatusOK {
1838 t.Errorf("the request that started the load answered %d", w.Code)
1839 }
1840 if n := reads.Load(); n != 1 {
1841 t.Errorf("the export was read %d times for one generation", n)
1842 }
1843 if n := len(h.srv.loadWaiting); n != 0 {
1844 t.Errorf("%d requests still hold a place among those that wait", n)
1845 }
1846}
1847
1848// A request's time runs from its arrival through its rendering: a request
1849// for a page that runs no git, held past its time before it renders,
1850// answers 503, and the server logs it.
1851func TestRenderingIsWithinTheDeadline(t *testing.T) {
1852 h := newHarness(t)
1853 h.page("/")
1854 h.srv.timeout = 50 * time.Millisecond
1855 var logged []string
1856 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
1857 h.srv.opened = func(export.Generation) { time.Sleep(100 * time.Millisecond) }
1858 if w := h.get("/"); w.Code != http.StatusServiceUnavailable || !bytes.Equal(w.Body.Bytes(), busyPage) {
1859 t.Errorf("a request that ran out of time before it rendered answered %d", w.Code)
1860 }
1861 if len(logged) != 1 || !strings.Contains(logged[0], "rendering plan: context deadline exceeded") {
1862 t.Errorf("the server logged %q", logged)
1863 }
1864 if n := len(h.srv.budget); n != 0 {
1865 t.Errorf("a page that stopped rendering kept %d pieces of the budget", n)
1866 }
1867}
1868
1869// A FIFO with a writer that sends no bytes keeps Read blocked until the
1870// request deadline. A FIFO without a writer must not block Open.
1871func TestStalledLoadReleasesGeneration(t *testing.T) {
1872 for _, writer := range []bool{false, true} {
1873 t.Run(fmt.Sprint(writer), func(t *testing.T) {
1874 h := newHarness(t)
1875 h.srv.timeout = 100 * time.Millisecond
1876 h.srv.log = func(error) {}
1877 old := h.active()
1878 data, err := os.ReadFile(old.ExportPath())
1879 if err != nil {
1880 t.Fatal(err)
1881 }
1882 if err := os.Remove(old.ExportPath()); err != nil {
1883 t.Fatal(err)
1884 }
1885 if err := syscall.Mkfifo(old.ExportPath(), 0600); err != nil {
1886 t.Fatal(err)
1887 }
1888 if writer {
1889 f, err := os.OpenFile(old.ExportPath(), os.O_RDWR|syscall.O_NONBLOCK, 0)
1890 if err != nil {
1891 t.Fatal(err)
1892 }
1893 defer f.Close()
1894 if _, err := f.Write([]byte("{")); err != nil {
1895 t.Fatal(err)
1896 }
1897 }
1898 if w := h.get("/"); w.Code != http.StatusServiceUnavailable {
1899 t.Fatalf("status = %d", w.Code)
1900 }
1901 eventually(t, "the stalled worker exits", func() bool { return len(h.srv.loaders) == 0 })
1902 h.srv.mu.Lock()
1903 cached := h.srv.cached
1904 h.srv.mu.Unlock()
1905 if cached != nil {
1906 t.Fatal("stalled load cached a snapshot")
1907 }
1908 if err := os.Remove(old.ExportPath()); err != nil {
1909 t.Fatal(err)
1910 }
1911 if err := os.WriteFile(old.ExportPath(), data, 0644); err != nil {
1912 t.Fatal(err)
1913 }
1914 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan"))
1915 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1916 t.Fatalf("generation retained: %v", err)
1917 }
1918 h.srv.timeout = requestTimeout
1919 if !strings.Contains(h.page("/app/knots/oc-a000001"), "The second plan") {
1920 t.Fatal("loader slot is not reusable")
1921 }
1922 })
1923 }
1924}
1925
1926// cancelInPhase cancels a real context on the third cancellation check
1927// inside a named processing function. It makes cancellation during CPU
1928// work deterministic without replacing decoding or graph traversal.
1929type cancelInPhase struct {
1930 context.Context
1931 cancel context.CancelFunc
1932 phase string
1933 checks int
1934}
1935
1936func (c *cancelInPhase) Err() error {
1937 var pcs [32]uintptr
1938 n := runtime.Callers(2, pcs[:])
1939 frames := runtime.CallersFrames(pcs[:n])
1940 for {
1941 frame, more := frames.Next()
1942 if strings.HasSuffix(frame.Function, c.phase) {
1943 c.checks++
1944 if c.checks == 3 {
1945 c.cancel()
1946 }
1947 break
1948 }
1949 if !more {
1950 break
1951 }
1952 }
1953 return c.Context.Err()
1954}
1955
1956func TestProcessingCancellationReleasesGeneration(t *testing.T) {
1957 for _, phase := range []string{".decodeValue", ".(*Export).ValidateContext", ".(*index).planPage", ".(*index).paths", ".(*index).milestones"} {
1958 t.Run(phase, func(t *testing.T) {
1959 h := newHarness(t)
1960 old := h.active()
1961 base, cancel := context.WithCancel(context.Background())
1962 defer cancel()
1963 ctx := &cancelInPhase{Context: base, cancel: cancel, phase: phase}
1964 l := &load{done: make(chan struct{}), cancel: cancel}
1965 h.srv.loads[l] = struct{}{}
1966 h.srv.loaders <- struct{}{}
1967 finished := make(chan struct{})
1968 go func() { h.srv.run(ctx, l); close(finished) }()
1969 select {
1970 case <-finished:
1971 case <-time.After(2 * time.Second):
1972 t.Fatal("processing did not stop")
1973 }
1974 if ctx.checks < 3 {
1975 t.Fatalf("phase was not reached: %d checks", ctx.checks)
1976 }
1977 if !errors.Is(l.err, context.Canceled) {
1978 t.Fatalf("load error = %v", l.err)
1979 }
1980 if h.srv.cached != nil || len(h.srv.loaders) != 0 || len(h.srv.loads) != 0 {
1981 t.Fatal("cancelled processing retained load state")
1982 }
1983 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan"))
1984 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1985 t.Fatalf("generation retained: %v", err)
1986 }
1987 if !strings.Contains(h.page("/app/knots/oc-a000001"), "The second plan") {
1988 t.Fatal("loader slot is not reusable")
1989 }
1990 })
1991 }
1992}