gunk-dev/the-valley

server_test.go

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