gunk-dev/the-valley

server_test.go

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