gunk-dev/the-valley

server_test.go

source9d44ba98f6b9main's published tip history
65.6 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// A file of exactly MaxFile bytes of newlines is shown to MaxLines lines,
690// and its page says where it stops. A README longer than a page shows is
691// shown in part.
692func TestLongFileIsShownInPart(t *testing.T) {
693 h := newHarness(t)
694 tip, bundle := h.commitMain("app: long files\n",
695 file{"100644", "newlines.txt", strings.Repeat("\n", MaxFile)},
696 file{"100644", "long/README.md", strings.Repeat("a line of the README\n", 2*MaxLines)},
697 file{"100644", "wide.txt", strings.Repeat("<", MaxFile)},
698 )
699 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
700
701 page := h.page("/app/source/blob/" + tip + "/newlines.txt")
702 last := fmt.Sprintf(`id="L%d"`, MaxLines)
703 if !strings.Contains(page, last) || strings.Contains(page, fmt.Sprintf(`id="L%d"`, MaxLines+1)) {
704 t.Errorf("the file of newlines is not shown to line %d", MaxLines)
705 }
706 if want := fmt.Sprintf("The page stops at line %d of %d.", MaxLines, MaxFile); !strings.Contains(page, want) {
707 t.Errorf("the page does not say %q", want)
708 }
709 if len(page) > MaxShown {
710 t.Errorf("the page of a file of newlines is %d bytes, past MaxShown", len(page))
711 }
712
713 // One line of MaxFile characters that each escape to four bytes is
714 // cut where MaxShown is reached.
715 page = h.page("/app/source/blob/" + tip + "/wide.txt")
716 if !strings.Contains(page, "The page stops at line 1 of 1.") || len(page) > MaxShown+64<<10 {
717 t.Errorf("the page of one wide line is %d bytes", len(page))
718 }
719
720 page = h.page("/app/source/tree/" + tip + "/long/")
721 if !strings.Contains(page, "This README is longer than a page shows, and only its start is shown.") {
722 t.Error("the long README is not marked as shown in part")
723 }
724 if n := strings.Count(page, "a line of the README"); n != MaxLines {
725 t.Errorf("the long README shows %d lines, not %d", n, MaxLines)
726 }
727}
728
729// A chain of knots as deep as the graph's knot limit allows renders its
730// milestone to MaxPlanDepth levels, counts every knot under it, and
731// names MaxPlanDepth parents in the deepest knot's trail. The plan page's
732// structure is built once for the generation. Siblings that block one
733// another in a cycle share the last stage of their path.
734func TestDeepPlan(t *testing.T) {
735 h := newHarness(t)
736 var chain []string
737 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
738 p := &e.Projects[0]
739 for i := range knot.MaxKnots - len(p.Knots) - 3 {
740 id := fmt.Sprintf("oc-c%06x", i)
741 k := export.Knot{ID: id, Type: "outcome", Status: "open", Active: true, State: "ready",
742 Title: fmt.Sprintf("Level %d of the chain", i), Created: "2026-10-01", CreatedBy: "operator"}
743 if i == 0 {
744 p.Roots = append(p.Roots, id)
745 } else {
746 k.Parent = chain[i-1]
747 p.Knots[len(p.Knots)-1].Children = []string{id}
748 }
749 chain = append(chain, id)
750 p.Knots = append(p.Knots, k)
751 }
752 // Under the first link, a path whose two last siblings wait on
753 // each other.
754 free, a, b := "oc-d000001", "oc-d000002", "oc-d000003"
755 for _, k := range []export.Knot{
756 {ID: free, BlockedBy: []string{}},
757 {ID: a, BlockedBy: []string{free, b}},
758 {ID: b, BlockedBy: []string{a}},
759 } {
760 k.Type, k.Status, k.State, k.Title, k.Parent = "outcome", "open", "blocked", "Sibling "+k.ID, chain[0]
761 p.Knots = append(p.Knots, k)
762 }
763 for i := range p.Knots {
764 if p.Knots[i].ID == chain[0] {
765 p.Knots[i].Children = append(p.Knots[i].Children, free, a, b)
766 }
767 }
768 })
769
770 page := h.page("/")
771 if want := fmt.Sprintf("%d of %d done", 0, len(chain)-1+3); !strings.Contains(page, want) {
772 t.Errorf("the chain's milestone does not count every knot under it as %q", want)
773 }
774 if !strings.Contains(page, `href="/app/knots/`+chain[MaxPlanDepth]+`"`) || strings.Contains(page, `href="/app/knots/`+chain[MaxPlanDepth+1]+`"`) {
775 t.Errorf("the chain's tree is not shown to %d levels", MaxPlanDepth)
776 }
777 if n := strings.Count(page, ">more on its page<"); n != 1 {
778 t.Errorf("%d rows say there is more on their page; the chain's deepest shown row does", n)
779 }
780 if len(page) > 256<<10 {
781 t.Errorf("the plan page is %d bytes", len(page))
782 }
783 paths := section(t, page, `id="paths-h"`, `id="ms-h"`)
784 stage := regexp.MustCompile(`<span class="stage-num">(\d+)</span><ul class="plain">(.*?)</ul>`)
785 var stages []string
786 for _, m := range stage.FindAllStringSubmatch(paths, -1) {
787 if strings.Contains(m[2], "Sibling") {
788 var ids []string
789 for _, id := range regexp.MustCompile(`"mono muted">(oc-d00000\d)<`).FindAllStringSubmatch(m[2], -1) {
790 ids = append(ids, id[1])
791 }
792 stages = append(stages, m[1]+":"+strings.Join(ids, ","))
793 }
794 }
795 if got := strings.Join(stages, " "); got != "1:oc-d000001 2:oc-d000002,oc-d000003" {
796 t.Errorf("the siblings' path has stages %q", got)
797 }
798
799 h.srv.mu.Lock()
800 plan := h.srv.cached.idx.plan
801 h.srv.mu.Unlock()
802 h.page("/")
803 h.srv.mu.Lock()
804 again := h.srv.cached.idx.plan
805 h.srv.mu.Unlock()
806 if plan != again {
807 t.Error("the plan page's structure was built again for the same generation")
808 }
809
810 deepest := chain[len(chain)-1]
811 page = h.page("/app/knots/" + deepest)
812 trail := section(t, page, `<nav class="trail"`, `</nav>`)
813 if n := strings.Count(trail, `<a href="/app/knots/`); n != MaxPlanDepth || !strings.Contains(trail, "<span>…</span>") {
814 t.Errorf("the deepest knot's trail names %d parents, or does not mark those above them", n)
815 }
816 if !strings.Contains(trail, chain[len(chain)-2]) || strings.Contains(trail, `"/app/knots/`+chain[len(chain)-2-MaxPlanDepth]+`"`) {
817 t.Error("the trail does not name the nearest parents alone")
818 }
819}
820
821// Every response carries the strict policy, and the policy admits the
822// page's one inline stylesheet and one inline script by their hashes and
823// nothing from another origin.
824func TestEveryResponseCarriesTheCSP(t *testing.T) {
825 h := newHarness(t)
826 for _, c := range []struct{ method, target string }{
827 {"GET", "/"},
828 {"GET", "/app/knots/oc-a000002"},
829 {"GET", "/app/source/"},
830 {"GET", "/app/source/tree/" + h.tip() + "/"},
831 {"GET", "/app/source/blob/" + h.tip() + "/README.md"},
832 {"GET", "/no/such/page"},
833 {"POST", "/"},
834 {"HEAD", "/"},
835 } {
836 w := h.do(c.method, c.target)
837 got := w.Header().Get("Content-Security-Policy")
838 if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" {
839 t.Errorf("%s %s answered with policy %q", c.method, c.target, got)
840 }
841 }
842 for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} {
843 if !strings.Contains(csp, directive) {
844 t.Errorf("the policy lacks %s", directive)
845 }
846 }
847 for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} {
848 if strings.Contains(csp, loose) {
849 t.Errorf("the policy holds %q", loose)
850 }
851 }
852
853 page := h.page("/")
854 inline := func(tag string) string {
855 t.Helper()
856 m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1)
857 if len(m) != 1 || strings.Count(page, "<"+tag) != 1 {
858 t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag)
859 }
860 sum := sha256.Sum256([]byte(m[0][1]))
861 return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
862 }
863 if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") {
864 t.Errorf("the policy does not admit the page's script, %s", hash)
865 }
866 if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") {
867 t.Errorf("the policy does not admit the page's stylesheet, %s", hash)
868 }
869 for _, external := range []string{"<link", " src=", "@import", "url("} {
870 if strings.Contains(page, external) {
871 t.Errorf("the plan page holds %q", external)
872 }
873 }
874}
875
876// A request serves everything from the generation it opened, though
877// another activates while it runs, and that generation outlives the
878// activation until the request releases it.
879func TestARequestKeepsItsGeneration(t *testing.T) {
880 h := newHarness(t)
881 paused, resume := make(chan export.Generation), make(chan struct{})
882 var once sync.Once
883 h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) }
884 served := make(chan *httptest.ResponseRecorder)
885 go func() {
886 w := httptest.NewRecorder()
887 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/knots/oc-a000001", nil))
888 served <- w
889 }()
890 old := <-paused
891
892 next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
893 if next.Sequence == old.Sequence {
894 t.Fatal("the publish did not activate a new generation")
895 }
896 if _, err := os.Stat(old.Dir); err != nil {
897 t.Fatalf("the generation a request holds was deleted: %v", err)
898 }
899 close(resume)
900 w := <-served
901 if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app&#39;s plan") || strings.Contains(body, "second plan") {
902 t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body)
903 }
904 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the second plan") {
905 t.Error("the next request does not serve the new generation")
906 }
907
908 // Released, the old generation goes with the next activation.
909 h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
910 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
911 t.Errorf("the released generation is still on disk: %v", err)
912 }
913}
914
915// eventually waits up to ten seconds for cond to hold.
916func eventually(t *testing.T, what string, cond func() bool) {
917 t.Helper()
918 for deadline := time.Now().Add(10 * time.Second); !cond(); time.Sleep(time.Millisecond) {
919 if time.Now().After(deadline) {
920 t.Fatalf("timed out waiting until %s", what)
921 }
922 }
923}
924
925// renamed changes the title of the fixture's first knot.
926func renamed(title string) func(*export.Export) {
927 return func(e *export.Export) { e.Projects[0].Knots[0].Title = title }
928}
929
930// Requests that wait for a generation together read its export once.
931// While it is read, a newer generation is read on its own, and at most
932// MaxLoads exports are read at once. A request whose load ends after a
933// newer generation was activated waits for that one, so every request is
934// served the generation active when its snapshot is ready, and an older
935// read that finishes last does not displace the newest snapshot.
936func TestExportLoadsCoalesce(t *testing.T) {
937 h := newHarness(t)
938 var mu sync.Mutex
939 loads := map[int64]int{}
940 holds := map[int64]chan struct{}{}
941 hold := func(g export.Generation) chan struct{} {
942 mu.Lock()
943 defer mu.Unlock()
944 if holds[g.Sequence] == nil {
945 holds[g.Sequence] = make(chan struct{})
946 }
947 return holds[g.Sequence]
948 }
949 h.srv.loading = func(g export.Generation) {
950 mu.Lock()
951 loads[g.Sequence]++
952 mu.Unlock()
953 <-hold(g)
954 }
955 loaded := func(g export.Generation) int {
956 mu.Lock()
957 defer mu.Unlock()
958 return loads[g.Sequence]
959 }
960 var opens atomic.Int32
961 h.srv.opened = func(export.Generation) { opens.Add(1) }
962 get := func(n int) chan *httptest.ResponseRecorder {
963 served := make(chan *httptest.ResponseRecorder, n)
964 for range n {
965 go func() {
966 w := httptest.NewRecorder()
967 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/knots/oc-a000001", nil))
968 served <- w
969 }()
970 }
971 return served
972 }
973 expect := func(served chan *httptest.ResponseRecorder, n int, title string) {
974 t.Helper()
975 for range n {
976 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
977 t.Errorf("a request answered %d, not with %q", w.Code, title)
978 }
979 }
980 }
981 waiting := func(n int) func() bool { return func() bool { return len(h.srv.loadWaiting) == n } }
982
983 first := h.active()
984 firstServed := get(10)
985 eventually(t, "ten requests wait for the first generation's read", func() bool {
986 return loaded(first) == 1 && len(h.srv.loadWaiting) == 10
987 })
988 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
989 secondServed := get(1)
990 eventually(t, "the second generation is read", func() bool { return loaded(second) == 1 })
991
992 // Both loaders are taken, so the third generation waits for one.
993 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
994 thirdServed := get(1)
995 eventually(t, "a request waits for the third generation", waiting(12))
996 time.Sleep(20 * time.Millisecond)
997 if n := loaded(third); n != 0 {
998 t.Errorf("a third export was read while %d were", MaxLoads)
999 }
1000 if n := opens.Load(); n != 0 {
1001 t.Errorf("%d requests opened a generation while they waited for its read", n)
1002 }
1003
1004 // The second read ends, and its request finds the third generation
1005 // active, and waits for that read with the third's request.
1006 close(hold(second))
1007 eventually(t, "the third generation is read", func() bool { return loaded(third) == 1 })
1008 close(hold(third))
1009 expect(secondServed, 1, "Readers browse the third plan")
1010 expect(thirdServed, 1, "Readers browse the third plan")
1011 close(hold(first))
1012 expect(firstServed, 10, "Readers browse the third plan")
1013
1014 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the third plan") {
1015 t.Error("the first generation's read displaced the third's")
1016 }
1017 for _, g := range []export.Generation{first, second, third} {
1018 if n := loaded(g); n != 1 {
1019 t.Errorf("generation %d's export was read %d times", g.Sequence, n)
1020 }
1021 }
1022}
1023
1024// Source requests past MaxGit wait, MaxWaiting of them, and one more
1025// answers 503 at once. A waiting request holds no generation, so an
1026// activation while the server is saturated deletes the old generation,
1027// and every waiting request serves the new one. A request's time runs
1028// from its arrival, so one that waits past it answers 503.
1029func TestSourceAdmission(t *testing.T) {
1030 h := newHarness(t)
1031 var admitted atomic.Int32
1032 release := make(chan struct{})
1033 h.srv.admitted = func() {
1034 admitted.Add(1)
1035 <-release
1036 }
1037 target := "/app/source/tree/" + h.tip() + "/"
1038 get := func(n int) chan *httptest.ResponseRecorder {
1039 served := make(chan *httptest.ResponseRecorder, n)
1040 for range n {
1041 go func() {
1042 w := httptest.NewRecorder()
1043 h.srv.ServeHTTP(w, httptest.NewRequest("GET", target, nil))
1044 served <- w
1045 }()
1046 }
1047 return served
1048 }
1049
1050 old := h.active()
1051 served := get(MaxGit + MaxWaiting)
1052 eventually(t, "every slot is taken and MaxWaiting requests wait", func() bool {
1053 return admitted.Load() == MaxGit && len(h.srv.waiting) == MaxWaiting
1054 })
1055 if w := h.get(target); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1056 t.Errorf("a source request past MaxWaiting answered %d, Retry-After %q", w.Code, w.Header().Get("Retry-After"))
1057 }
1058 h.page("/") // a page that runs no git is served still
1059
1060 tip, bundle := h.commitMain("app: a commit while the server is saturated\n", file{"100644", "saturated.txt", "saturated\n"})
1061 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1062 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1063 t.Errorf("a generation no request had opened outlived the activation: %v", err)
1064 }
1065 close(release)
1066 for range MaxGit + MaxWaiting {
1067 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "/app/source/tree/"+tip+"/") {
1068 t.Errorf("a waiting request answered %d, not from the new generation", w.Code)
1069 }
1070 }
1071
1072 // A request that waits past its time answers 503. Those that held
1073 // the slots meanwhile ran out of time too.
1074 h.srv.timeout = 200 * time.Millisecond
1075 h.srv.log = func(error) {}
1076 admitted.Store(0)
1077 release = make(chan struct{})
1078 held := get(MaxGit)
1079 eventually(t, "every slot is taken", func() bool { return admitted.Load() == MaxGit })
1080 start := time.Now()
1081 if w := h.get(target); w.Code != http.StatusServiceUnavailable {
1082 t.Errorf("a request that waited past its time answered %d", w.Code)
1083 }
1084 if waited := time.Since(start); waited > 5*time.Second {
1085 t.Errorf("a request waited %v past its time of 200ms", waited)
1086 }
1087 close(release)
1088 for range MaxGit {
1089 if w := <-held; w.Code != http.StatusServiceUnavailable {
1090 t.Errorf("a request that ran out of time answered %d", w.Code)
1091 }
1092 }
1093}
1094
1095// stallingListener accepts connections whose writes stall until release
1096// is closed, while stall is set. Each sends on stalled the first time one
1097// of its writes stalls.
1098type stallingListener struct {
1099 net.Listener
1100 stall atomic.Bool
1101 release chan struct{}
1102 stalled chan struct{}
1103}
1104
1105func (l *stallingListener) Accept() (net.Conn, error) {
1106 c, err := l.Listener.Accept()
1107 if err != nil || !l.stall.Load() {
1108 return c, err
1109 }
1110 return &stallingConn{Conn: c, l: l}, nil
1111}
1112
1113type stallingConn struct {
1114 net.Conn
1115 l *stallingListener
1116 once sync.Once
1117}
1118
1119func (c *stallingConn) Write(p []byte) (int, error) {
1120 c.once.Do(func() { c.l.stalled <- struct{}{} })
1121 <-c.l.release
1122 return c.Conn.Write(p)
1123}
1124
1125// Readers that never read their responses hold no git slot and no
1126// generation: more of them than MaxGit and MaxWaiting together are
1127// stalled writing, and a new reader is still served, and an activation
1128// deletes the generation they were served from.
1129func TestSlowReadersHoldNothing(t *testing.T) {
1130 h := newHarness(t)
1131 ln, err := net.Listen("tcp", "127.0.0.1:0")
1132 if err != nil {
1133 t.Fatal(err)
1134 }
1135 n := MaxGit + MaxWaiting + 4
1136 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
1137 sl.stall.Store(true)
1138 srv := &http.Server{Handler: h.srv}
1139 go srv.Serve(sl)
1140 var conns []net.Conn
1141 defer func() {
1142 close(sl.release)
1143 for _, c := range conns {
1144 c.Close()
1145 }
1146 srv.Close()
1147 }()
1148
1149 old := h.active()
1150 target := "/app/source/blob/" + h.tip() + "/docs/guide.md"
1151 for range n {
1152 c, err := net.Dial("tcp", ln.Addr().String())
1153 if err != nil {
1154 t.Fatal(err)
1155 }
1156 conns = append(conns, c)
1157 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
1158 }
1159 for i := range n {
1160 select {
1161 case <-sl.stalled:
1162 case <-time.After(10 * time.Second):
1163 t.Fatalf("%d of %d slow readers' responses were written; the rest wait", i, n)
1164 }
1165 }
1166 sl.stall.Store(false)
1167 if len(h.srv.slots) != 0 || len(h.srv.waiting) != 0 {
1168 t.Errorf("slow readers hold %d git slots, and %d requests wait", len(h.srv.slots), len(h.srv.waiting))
1169 }
1170
1171 client := &http.Client{Timeout: 10 * time.Second}
1172 resp, err := client.Get("http://" + ln.Addr().String() + target)
1173 if err != nil {
1174 t.Fatal(err)
1175 }
1176 resp.Body.Close()
1177 if resp.StatusCode != http.StatusOK {
1178 t.Errorf("a new reader answered %d while slow readers stall", resp.StatusCode)
1179 }
1180 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(*export.Export) {})
1181 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1182 t.Errorf("the generation slow readers were served from outlived the activation: %v", err)
1183 }
1184}
1185
1186// Before the first activation the server says nothing is published, and
1187// it answers GET and HEAD alone.
1188func TestNothingPublishedAndMethods(t *testing.T) {
1189 store, err := export.OpenStore(t.TempDir(), nil)
1190 if err != nil {
1191 t.Fatal(err)
1192 }
1193 srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }})
1194 w := httptest.NewRecorder()
1195 srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
1196 if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") {
1197 t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body)
1198 }
1199
1200 h := newHarness(t)
1201 for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} {
1202 w := h.do(method, "/")
1203 if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" {
1204 t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow"))
1205 }
1206 }
1207}
1208
1209// tooLarge checks that GET target answers with the one short page that
1210// says a page is too large.
1211func (h *harness) tooLarge(target string) {
1212 h.t.Helper()
1213 w := h.get(target)
1214 if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) {
1215 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())
1216 }
1217 if n := len(h.srv.budget); n != 0 {
1218 h.t.Errorf("GET %s kept %d pieces of the budget", target, n)
1219 }
1220}
1221
1222// A response's body is at most MaxResponse bytes. A page that would pass
1223// the bound answers with the one short page that says it is too large,
1224// and the failure is logged: a knot whose body passes MaxResponse, and,
1225// under a smaller bound, a file, a directory, a page of history and the
1226// plan page. A page within the bound is served on each route.
1227func TestPageTooLarge(t *testing.T) {
1228 h := newHarness(t)
1229 var logged []string
1230 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
1231 files := []file{{"100644", "wide.txt", strings.Repeat("<", 16<<10)}}
1232 for i := range 32 {
1233 files = append(files, file{"100644", fmt.Sprintf("wide/%02d-%s", i, strings.Repeat("n", 1000)), "x\n"})
1234 }
1235 h.commitMain("app: a wide file and a wide directory\n", files...)
1236 var tip, bundle string
1237 for i := range 8 {
1238 tip, bundle = h.commitMain(fmt.Sprintf("%d %s\n", i, strings.Repeat(`"`, maxLogText)))
1239 }
1240 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
1241 p := &e.Projects[0]
1242 p.SourceTip = tip
1243 p.Knots[0].Body = strings.Repeat("a", MaxResponse)
1244 for i := range 100 {
1245 p.Knots = append(p.Knots, export.Knot{ID: fmt.Sprintf("oc-e%06x", i), Type: "outcome", Status: "open",
1246 Active: true, State: "ready", Title: strings.Repeat(`"`, knot.MaxTitle), Created: "2026-10-01", CreatedBy: "operator"})
1247 }
1248 })
1249
1250 h.tooLarge("/app/knots/" + h.f.Export.Projects[0].Knots[0].ID)
1251 h.page("/app/knots/oc-a000002")
1252
1253 h.srv.maxResponse = 32 << 10
1254 at := "/app/source/blob/" + tip + "/"
1255 h.tooLarge(at + "wide.txt")
1256 h.page(at + "docs/guide.md")
1257 at = "/app/source/tree/" + tip + "/"
1258 h.tooLarge(at + "wide/")
1259 h.page(at + "docs/")
1260 h.tooLarge("/app/source/log/" + tip)
1261 h.page("/app/source/log/" + tip + "?skip=8")
1262 h.tooLarge("/")
1263
1264 if len(logged) != 5 {
1265 t.Errorf("%d failures were logged for 5 pages too large: %q", len(logged), logged)
1266 }
1267 for _, l := range logged {
1268 if !strings.Contains(l, "larger than") {
1269 t.Errorf("the server logged %q", l)
1270 }
1271 }
1272 if len(tooLargePage) > 16<<10 {
1273 t.Errorf("the page that says a page is too large is %d bytes", len(tooLargePage))
1274 }
1275}
1276
1277// Rendered responses share a budget of MaxBuffered bytes, which each
1278// holds from when it starts rendering until it is written. Readers that
1279// never read, asking for twice the budget in all, hold no more than it:
1280// once their pages fill it, a page it has no room for answers 503 at
1281// once, and a small page that fits is still served. The server's heap
1282// grows by no more than the budget, and the budget is whole again once
1283// the readers read.
1284func TestSlowReadersShareTheBudget(t *testing.T) {
1285 h := newHarness(t)
1286 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
1287 e.Projects[0].Knots[0].Body = strings.Repeat("a line of a long body\n", (4<<20)/22)
1288 })
1289 target := "/app/knots/" + h.f.Export.Projects[0].Knots[0].ID
1290 size := len(h.page(target))
1291 pieces := (size + pieceSize - 1) / pieceSize
1292 fit := cap(h.srv.budget) / pieces
1293 n := 2*MaxBuffered/size + 1
1294
1295 ln, err := net.Listen("tcp", "127.0.0.1:0")
1296 if err != nil {
1297 t.Fatal(err)
1298 }
1299 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
1300 sl.stall.Store(true)
1301 srv := &http.Server{Handler: h.srv}
1302 go srv.Serve(sl)
1303 var conns []net.Conn
1304 released := false
1305 defer func() {
1306 if !released {
1307 close(sl.release)
1308 }
1309 for _, c := range conns {
1310 c.Close()
1311 }
1312 srv.Close()
1313 }()
1314
1315 var before runtime.MemStats
1316 runtime.GC()
1317 runtime.ReadMemStats(&before)
1318 // One reader at a time, each stalled before the next asks, so the
1319 // readers that fill the budget are the first fit of them.
1320 for i := range n {
1321 c, err := net.Dial("tcp", ln.Addr().String())
1322 if err != nil {
1323 t.Fatal(err)
1324 }
1325 conns = append(conns, c)
1326 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
1327 select {
1328 case <-sl.stalled:
1329 case <-time.After(10 * time.Second):
1330 t.Fatalf("reader %d of %d was not answered", i+1, n)
1331 }
1332 }
1333 sl.stall.Store(false)
1334 var after runtime.MemStats
1335 runtime.GC()
1336 runtime.ReadMemStats(&after)
1337 if held := len(h.srv.budget); held != fit*pieces {
1338 t.Errorf("slow readers hold %d pieces; %d pages of %d pieces fit", held, fit, pieces)
1339 }
1340 if grew := int64(after.HeapAlloc) - int64(before.HeapAlloc); grew > MaxBuffered+8<<20 {
1341 t.Errorf("%d slow readers of %d bytes each grew the heap by %d bytes, past MaxBuffered", n, size, grew)
1342 }
1343
1344 client := &http.Client{Timeout: 10 * time.Second}
1345 get := func(target string) (int, string) {
1346 t.Helper()
1347 resp, err := client.Get("http://" + ln.Addr().String() + target)
1348 if err != nil {
1349 t.Fatal(err)
1350 }
1351 defer resp.Body.Close()
1352 io.Copy(io.Discard, resp.Body)
1353 return resp.StatusCode, resp.Header.Get("Retry-After")
1354 }
1355 if code, retry := get(target); code != http.StatusServiceUnavailable || retry == "" {
1356 t.Errorf("a page the budget has no room for answered %d, Retry-After %q", code, retry)
1357 }
1358 if code, _ := get("/app/knots/oc-a000002"); code != http.StatusOK {
1359 t.Errorf("a small page answered %d while slow readers hold most of the budget", code)
1360 }
1361
1362 close(sl.release)
1363 released = true
1364 codes := map[int]int{}
1365 for _, c := range conns {
1366 c.SetReadDeadline(time.Now().Add(10 * time.Second))
1367 resp, err := http.ReadResponse(bufio.NewReader(c), nil)
1368 if err != nil {
1369 t.Fatal(err)
1370 }
1371 read, err := io.Copy(io.Discard, resp.Body)
1372 resp.Body.Close()
1373 if err != nil || resp.StatusCode == http.StatusOK && read != int64(size) {
1374 t.Errorf("a slow reader read %d bytes of %d: %v", read, size, err)
1375 }
1376 codes[resp.StatusCode]++
1377 }
1378 if codes[http.StatusOK] != fit || codes[http.StatusServiceUnavailable] != n-fit {
1379 t.Errorf("of %d slow readers, %d were served and %d answered 503; %d pages fit the budget",
1380 n, codes[http.StatusOK], codes[http.StatusServiceUnavailable], fit)
1381 }
1382 eventually(t, "the budget is whole again", func() bool { return len(h.srv.budget) == 0 })
1383}
1384
1385// A load starts only once a request that waits for it takes a loader
1386// slot. While MaxLoads loads run, a request for a newer generation waits
1387// for a slot, holding no generation, until its time runs out, whatever
1388// its route, or its reader goes away. Neither leaves a load behind.
1389func TestExportLoadWaitsEnd(t *testing.T) {
1390 h := newHarness(t)
1391 var mu sync.Mutex
1392 var logged []string
1393 h.srv.log = func(err error) {
1394 mu.Lock()
1395 defer mu.Unlock()
1396 logged = append(logged, err.Error())
1397 }
1398 loads := map[int64]int{}
1399 hold := make(chan struct{})
1400 h.srv.loading = func(g export.Generation) {
1401 mu.Lock()
1402 loads[g.Sequence]++
1403 mu.Unlock()
1404 <-hold
1405 }
1406 loaded := func(g export.Generation) int {
1407 mu.Lock()
1408 defer mu.Unlock()
1409 return loads[g.Sequence]
1410 }
1411 serve := func(r *http.Request) chan *httptest.ResponseRecorder {
1412 served := make(chan *httptest.ResponseRecorder, 1)
1413 go func() {
1414 w := httptest.NewRecorder()
1415 h.srv.ServeHTTP(w, r)
1416 served <- w
1417 }()
1418 return served
1419 }
1420 expect := func(served chan *httptest.ResponseRecorder, title string) {
1421 t.Helper()
1422 select {
1423 case w := <-served:
1424 if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
1425 t.Errorf("a request answered %d, not with %q", w.Code, title)
1426 }
1427 case <-time.After(10 * time.Second):
1428 t.Fatalf("a request was not answered with %q", title)
1429 }
1430 }
1431
1432 first := h.active()
1433 firstServed := serve(httptest.NewRequest("GET", "/", nil))
1434 eventually(t, "the first generation is read", func() bool { return loaded(first) == 1 })
1435 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1436 secondServed := serve(httptest.NewRequest("GET", "/", nil))
1437 eventually(t, "both loader slots are taken", func() bool { return loaded(second) == 1 })
1438
1439 // A request that runs no git runs out of time waiting, and answers
1440 // 503.
1441 h.srv.timeout = 200 * time.Millisecond
1442 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1443 select {
1444 case w := <-serve(httptest.NewRequest("GET", "/app/knots/oc-a000001", nil)):
1445 if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1446 t.Errorf("a request that waited past its time for a read answered %d", w.Code)
1447 }
1448 case <-time.After(10 * time.Second):
1449 t.Fatal("a request waits for a read past its time of 200ms")
1450 }
1451
1452 // A request whose reader goes away stops waiting, and answers
1453 // nothing.
1454 h.srv.timeout = time.Hour
1455 fourth := h.publish(exporttest.SignedAt.Add(3*time.Minute), nil, renamed("Readers browse the fourth plan"))
1456 ctx, cancel := context.WithCancel(context.Background())
1457 defer cancel()
1458 gone := serve(httptest.NewRequest("GET", "/", nil).WithContext(ctx))
1459 eventually(t, "a request waits for the fourth generation", func() bool { return len(h.srv.loadWaiting) == 3 })
1460 cancel()
1461 select {
1462 case w := <-gone:
1463 if w.Body.Len() != 0 {
1464 t.Errorf("a request whose reader went away answered %d", w.Code)
1465 }
1466 case <-time.After(10 * time.Second):
1467 t.Fatal("a request whose reader went away still waits")
1468 }
1469
1470 h.srv.mu.Lock()
1471 left := len(h.srv.loads)
1472 h.srv.mu.Unlock()
1473 if left != MaxLoads {
1474 t.Errorf("%d loads may be joined; only the %d that run are wanted", left, MaxLoads)
1475 }
1476 h.publish(exporttest.SignedAt.Add(4*time.Minute), nil, renamed("Readers browse the fifth plan"))
1477 for _, g := range []export.Generation{third, fourth} {
1478 if _, err := os.Stat(g.Dir); !os.IsNotExist(err) {
1479 t.Errorf("generation %d outlived an activation after its request gave up: %v", g.Sequence, err)
1480 }
1481 }
1482
1483 // The first two reads end, and their requests are served the newest
1484 // generation.
1485 close(hold)
1486 expect(firstServed, "Readers browse the fifth plan")
1487 expect(secondServed, "Readers browse the fifth plan")
1488 for _, g := range []export.Generation{third, fourth} {
1489 if n := loaded(g); n != 0 {
1490 t.Errorf("generation %d's export was read %d times after every request for it gave up", g.Sequence, n)
1491 }
1492 }
1493 mu.Lock()
1494 defer mu.Unlock()
1495 if len(logged) != 1 || !strings.Contains(logged[0], "deadline exceeded") {
1496 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
1497 }
1498}
1499
1500// A load that reads slowly does not hold the request that waits for it:
1501// the request answers 503 at its deadline. With no request left waiting,
1502// the load stops reading part way through the export, caches nothing, and
1503// gives back its generation, which the next activation deletes. A load
1504// that ends is kept, and the requests after it are served without another
1505// read.
1506func TestSlowLoadEndsWithItsRequests(t *testing.T) {
1507 h := newHarness(t)
1508 h.srv.timeout = 200 * time.Millisecond
1509 var mu sync.Mutex
1510 var logged []string
1511 h.srv.log = func(err error) {
1512 mu.Lock()
1513 defer mu.Unlock()
1514 logged = append(logged, err.Error())
1515 }
1516 var reads atomic.Int32
1517 h.srv.loading = func(export.Generation) { reads.Add(1) }
1518
1519 // The active generation's export.json becomes a pipe the test writes
1520 // a few bytes at a time, as a slow disk would give it: all of it
1521 // takes about 4 seconds, twenty times the request's time.
1522 old := h.active()
1523 data, err := os.ReadFile(old.ExportPath())
1524 if err != nil {
1525 t.Fatal(err)
1526 }
1527 if err := os.Remove(old.ExportPath()); err != nil {
1528 t.Fatal(err)
1529 }
1530 if err := syscall.Mkfifo(old.ExportPath(), 0o600); err != nil {
1531 t.Fatal(err)
1532 }
1533 piece := max(1, len(data)/200)
1534 wrote := make(chan error, 1)
1535 go func() {
1536 f, err := os.OpenFile(old.ExportPath(), os.O_WRONLY, 0)
1537 if err != nil {
1538 wrote <- err
1539 return
1540 }
1541 defer f.Close()
1542 for p := data; len(p) > 0; p = p[min(len(p), piece):] {
1543 if _, err := f.Write(p[:min(len(p), piece)]); err != nil {
1544 wrote <- err
1545 return
1546 }
1547 time.Sleep(20 * time.Millisecond)
1548 }
1549 wrote <- nil
1550 }()
1551
1552 start := time.Now()
1553 if w := h.get("/"); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1554 t.Errorf("a request whose load ran past its time answered %d", w.Code)
1555 }
1556 if waited := time.Since(start); waited > 2*time.Second {
1557 t.Errorf("a request waited %v for a slow load, past its time of 200ms", waited)
1558 }
1559 select {
1560 case err := <-wrote:
1561 if !errors.Is(err, syscall.EPIPE) {
1562 t.Errorf("the load read the whole export after its request gave up: the writer ended with %v", err)
1563 }
1564 case <-time.After(10 * time.Second):
1565 t.Fatal("the load still reads the export")
1566 }
1567 eventually(t, "the load ends", func() bool { return len(h.srv.loaders) == 0 })
1568 h.srv.mu.Lock()
1569 cached, loads := h.srv.cached, len(h.srv.loads)
1570 h.srv.mu.Unlock()
1571 if cached != nil || loads != 0 {
1572 t.Errorf("a load that stopped left a snapshot %v and %d loads", cached != nil, loads)
1573 }
1574 // The store reads the active export.json when it takes an upload.
1575 if err := os.Remove(old.ExportPath()); err != nil {
1576 t.Fatal(err)
1577 }
1578 if err := os.WriteFile(old.ExportPath(), data, 0o644); err != nil {
1579 t.Fatal(err)
1580 }
1581 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1582 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1583 t.Errorf("the generation a stopped load opened outlived an activation: %v", err)
1584 }
1585
1586 h.srv.timeout = requestTimeout
1587 for range 3 {
1588 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the second plan") {
1589 t.Error("a request after the stopped load is not served the new generation")
1590 }
1591 }
1592 if n := reads.Load(); n != 2 {
1593 t.Errorf("exports were read %d times: once in part, and once for the new generation", n)
1594 }
1595 mu.Lock()
1596 defer mu.Unlock()
1597 if len(logged) != 1 || !strings.Contains(logged[0], "export to be read: context deadline exceeded") {
1598 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
1599 }
1600}
1601
1602// openFiles is the number of files the process holds open, and false
1603// where the system does not list them.
1604func openFiles(t *testing.T) (int, bool) {
1605 t.Helper()
1606 entries, err := os.ReadDir("/proc/self/fd")
1607 if err != nil {
1608 return 0, false
1609 }
1610 return len(entries), true
1611}
1612
1613// A flood of requests while a load runs: MaxLoadWaiting of them wait, and
1614// the rest answer 503 at once, unlogged. A waiting request holds no
1615// generation, so the goroutines and files the server holds stay within a
1616// bound however large the flood. Once the load ends, every request that
1617// waited is served from its one read.
1618func TestLoadFlood(t *testing.T) {
1619 h := newHarness(t)
1620 var reads atomic.Int32
1621 reading, hold := make(chan struct{}, 1), make(chan struct{})
1622 h.srv.loading = func(export.Generation) {
1623 reads.Add(1)
1624 reading <- struct{}{}
1625 <-hold
1626 }
1627 get := func(n int) chan *httptest.ResponseRecorder {
1628 served := make(chan *httptest.ResponseRecorder, n)
1629 for range n {
1630 go func() {
1631 w := httptest.NewRecorder()
1632 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
1633 served <- w
1634 }()
1635 }
1636 return served
1637 }
1638
1639 first := get(1)
1640 select {
1641 case <-reading:
1642 case <-time.After(10 * time.Second):
1643 t.Fatal("no load started")
1644 }
1645 goroutines := runtime.NumGoroutine()
1646 files, listed := openFiles(t)
1647
1648 flood := 4 * MaxLoadWaiting
1649 served := get(flood)
1650 refused := flood - (MaxLoadWaiting - 1)
1651 for range refused {
1652 if w := <-served; w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1653 t.Fatalf("a request past MaxLoadWaiting answered %d", w.Code)
1654 }
1655 }
1656 if n := len(h.srv.loadWaiting); n != MaxLoadWaiting {
1657 t.Errorf("%d requests wait for the load, not %d", n, MaxLoadWaiting)
1658 }
1659 const slack = 8
1660 eventually(t, "the refused requests' goroutines end", func() bool {
1661 return runtime.NumGoroutine() <= goroutines+MaxLoadWaiting-1+slack
1662 })
1663 if n, _ := openFiles(t); listed && n > files+slack {
1664 t.Errorf("the flood holds %d files open, %d more than before it", n, n-files)
1665 }
1666
1667 close(hold)
1668 for range MaxLoadWaiting - 1 {
1669 if w := <-served; w.Code != http.StatusOK {
1670 t.Errorf("a request that waited for the load answered %d", w.Code)
1671 }
1672 }
1673 if w := <-first; w.Code != http.StatusOK {
1674 t.Errorf("the request that started the load answered %d", w.Code)
1675 }
1676 if n := reads.Load(); n != 1 {
1677 t.Errorf("the export was read %d times for one generation", n)
1678 }
1679 if n := len(h.srv.loadWaiting); n != 0 {
1680 t.Errorf("%d requests still hold a place among those that wait", n)
1681 }
1682}
1683
1684// A request's time runs from its arrival through its rendering: a request
1685// for a page that runs no git, held past its time before it renders,
1686// answers 503, and the server logs it.
1687func TestRenderingIsWithinTheDeadline(t *testing.T) {
1688 h := newHarness(t)
1689 h.page("/")
1690 h.srv.timeout = 50 * time.Millisecond
1691 var logged []string
1692 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
1693 h.srv.opened = func(export.Generation) { time.Sleep(100 * time.Millisecond) }
1694 if w := h.get("/"); w.Code != http.StatusServiceUnavailable || !bytes.Equal(w.Body.Bytes(), busyPage) {
1695 t.Errorf("a request that ran out of time before it rendered answered %d", w.Code)
1696 }
1697 if len(logged) != 1 || !strings.Contains(logged[0], "rendering plan: context deadline exceeded") {
1698 t.Errorf("the server logged %q", logged)
1699 }
1700 if n := len(h.srv.budget); n != 0 {
1701 t.Errorf("a page that stopped rendering kept %d pieces of the budget", n)
1702 }
1703}
1704
1705// A FIFO with a writer that sends no bytes keeps Read blocked until the
1706// request deadline. A FIFO without a writer must not block Open.
1707func TestStalledLoadReleasesGeneration(t *testing.T) {
1708 for _, writer := range []bool{false, true} {
1709 t.Run(fmt.Sprint(writer), func(t *testing.T) {
1710 h := newHarness(t)
1711 h.srv.timeout = 100 * time.Millisecond
1712 h.srv.log = func(error) {}
1713 old := h.active()
1714 data, err := os.ReadFile(old.ExportPath())
1715 if err != nil {
1716 t.Fatal(err)
1717 }
1718 if err := os.Remove(old.ExportPath()); err != nil {
1719 t.Fatal(err)
1720 }
1721 if err := syscall.Mkfifo(old.ExportPath(), 0600); err != nil {
1722 t.Fatal(err)
1723 }
1724 if writer {
1725 f, err := os.OpenFile(old.ExportPath(), os.O_RDWR|syscall.O_NONBLOCK, 0)
1726 if err != nil {
1727 t.Fatal(err)
1728 }
1729 defer f.Close()
1730 if _, err := f.Write([]byte("{")); err != nil {
1731 t.Fatal(err)
1732 }
1733 }
1734 if w := h.get("/"); w.Code != http.StatusServiceUnavailable {
1735 t.Fatalf("status = %d", w.Code)
1736 }
1737 eventually(t, "the stalled worker exits", func() bool { return len(h.srv.loaders) == 0 })
1738 h.srv.mu.Lock()
1739 cached := h.srv.cached
1740 h.srv.mu.Unlock()
1741 if cached != nil {
1742 t.Fatal("stalled load cached a snapshot")
1743 }
1744 if err := os.Remove(old.ExportPath()); err != nil {
1745 t.Fatal(err)
1746 }
1747 if err := os.WriteFile(old.ExportPath(), data, 0644); err != nil {
1748 t.Fatal(err)
1749 }
1750 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan"))
1751 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1752 t.Fatalf("generation retained: %v", err)
1753 }
1754 h.srv.timeout = requestTimeout
1755 if !strings.Contains(h.page("/app/knots/oc-a000001"), "The second plan") {
1756 t.Fatal("loader slot is not reusable")
1757 }
1758 })
1759 }
1760}
1761
1762// cancelInPhase cancels a real context on the third cancellation check
1763// inside a named processing function. It makes cancellation during CPU
1764// work deterministic without replacing decoding or graph traversal.
1765type cancelInPhase struct {
1766 context.Context
1767 cancel context.CancelFunc
1768 phase string
1769 checks int
1770}
1771
1772func (c *cancelInPhase) Err() error {
1773 var pcs [32]uintptr
1774 n := runtime.Callers(2, pcs[:])
1775 frames := runtime.CallersFrames(pcs[:n])
1776 for {
1777 frame, more := frames.Next()
1778 if strings.HasSuffix(frame.Function, c.phase) {
1779 c.checks++
1780 if c.checks == 3 {
1781 c.cancel()
1782 }
1783 break
1784 }
1785 if !more {
1786 break
1787 }
1788 }
1789 return c.Context.Err()
1790}
1791
1792func TestProcessingCancellationReleasesGeneration(t *testing.T) {
1793 for _, phase := range []string{".decodeValue", ".(*Export).ValidateContext", ".(*index).planPage", ".(*index).paths", ".(*index).milestones"} {
1794 t.Run(phase, func(t *testing.T) {
1795 h := newHarness(t)
1796 old := h.active()
1797 base, cancel := context.WithCancel(context.Background())
1798 defer cancel()
1799 ctx := &cancelInPhase{Context: base, cancel: cancel, phase: phase}
1800 l := &load{done: make(chan struct{}), cancel: cancel}
1801 h.srv.loads[l] = struct{}{}
1802 h.srv.loaders <- struct{}{}
1803 finished := make(chan struct{})
1804 go func() { h.srv.run(ctx, l); close(finished) }()
1805 select {
1806 case <-finished:
1807 case <-time.After(2 * time.Second):
1808 t.Fatal("processing did not stop")
1809 }
1810 if ctx.checks < 3 {
1811 t.Fatalf("phase was not reached: %d checks", ctx.checks)
1812 }
1813 if !errors.Is(l.err, context.Canceled) {
1814 t.Fatalf("load error = %v", l.err)
1815 }
1816 if h.srv.cached != nil || len(h.srv.loaders) != 0 || len(h.srv.loads) != 0 {
1817 t.Fatal("cancelled processing retained load state")
1818 }
1819 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan"))
1820 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1821 t.Fatalf("generation retained: %v", err)
1822 }
1823 if !strings.Contains(h.page("/app/knots/oc-a000001"), "The second plan") {
1824 t.Fatal("loader slot is not reusable")
1825 }
1826 })
1827 }
1828}