gunk-dev/the-valley

server_test.go

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