gunk-dev/the-valley

server_test.go

source7db83f346570main's published tip history
82.0 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 t := h.t
777 t.Helper()
778 repo := h.f.Repos["app"]
779 base := git(t, repo, nil, "rev-parse", export.MainRef)
780 var b bytes.Buffer
781 commit := func(ref string, mark, at int, message string) {
782 who := fmt.Sprintf("Example Author <author@example.org> %d +0000", 1791190800+at)
783 fmt.Fprintf(&b, "commit %s\nmark :%d\nauthor %s\ncommitter %s\ndata %d\n%s\n", ref, mark, who, who, len(message), message)
784 }
785 for i := range length {
786 for l := range n {
787 commit(fmt.Sprintf("refs/heads/line-%d", l), 1+i*n+l, i*n+l, fmt.Sprintf("line %d, commit %d\n", l, i))
788 if i == 0 {
789 fmt.Fprintf(&b, "from %s\n", base)
790 }
791 }
792 }
793 commit("refs/heads/main", 1+length*n, length*n, fmt.Sprintf("merge %d lines\n", n))
794 fmt.Fprintf(&b, "from :%d\n", 1+(length-1)*n)
795 for l := 1; l < n; l++ {
796 fmt.Fprintf(&b, "merge :%d\n", 1+(length-1)*n+l)
797 }
798 git(t, repo, b.Bytes(), "fast-import", "--quiet")
799 for l := range n {
800 git(t, repo, nil, "update-ref", "-d", fmt.Sprintf("refs/heads/line-%d", l))
801 }
802 tip = git(t, repo, nil, "rev-parse", export.MainRef)
803 bundle = filepath.Join(t.TempDir(), "app.bundle")
804 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
805 return tip, bundle
806}
807
808// logged is the commits a page of history lists, in order.
809var logged = regexp.MustCompile(`<td class="name"><a href="/app/source/tree/([0-9a-f]+)/">`)
810
811// A page of history links the older page as the commits it leaves to
812// show next, so the history of a merge whose lines run past a page is
813// shown whole: following the older links from the tip shows every commit
814// main reaches, each once. A page past the first links the newest page. A
815// ?from= that is not ascending, names a commit the page's commit does
816// not reach, or names more than MaxFrontier commits answers 404.
817func TestHistoryAcrossMerges(t *testing.T) {
818 h := newHarness(t)
819 tip, bundle := h.lines(2, 60)
820 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
821
822 at := "/app/source/log/" + tip
823 seen := map[string]int{}
824 merged := false
825 for target, pages := at, 0; target != ""; pages++ {
826 if pages > 10 {
827 t.Fatal("the older links do not end")
828 }
829 page := h.page(target)
830 for _, m := range logged.FindAllStringSubmatch(page, -1) {
831 seen[m[1]]++
832 }
833 if target != at && !strings.Contains(page, `href="`+at+`">Newest`) {
834 t.Errorf("%s does not link the newest page", target)
835 }
836 target = ""
837 if m := regexp.MustCompile(`href="(/app/source/log/[0-9a-f]+\?from=([0-9a-f,]+))">Older`).FindStringSubmatch(page); m != nil {
838 target, merged = m[1], merged || strings.Contains(m[2], ",")
839 }
840 }
841 all := strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", tip))
842 if len(seen) != len(all) {
843 t.Errorf("the older links show %d commits of the %d main reaches", len(seen), len(all))
844 }
845 for _, id := range all {
846 if seen[id] != 1 {
847 t.Errorf("the older links show %s %d times", id, seen[id])
848 }
849 }
850 if !merged {
851 t.Error("no page ends with both lines still to show")
852 }
853
854 line := strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", "--max-count=2", tip+"^2"))
855 slices.Sort(line)
856 for _, from := range []string{
857 line[1] + "," + line[0], // not ascending
858 line[0] + "," + line[0], // twice
859 tip, // not reached from the page's commit
860 strings.Repeat("1", 40), // no object
861 strings.Repeat(line[0]+",", MaxFrontier) + line[1],
862 line[0][:12],
863 "",
864 } {
865 target := "/app/source/log/" + line[1] + "?from=" + from
866 if w := h.get(target); w.Code != http.StatusNotFound {
867 t.Errorf("GET %s answered %d", target, w.Code)
868 }
869 }
870 if w := h.get(at + "?from=" + line[0] + "&from=" + line[1]); w.Code != http.StatusNotFound {
871 t.Errorf("two from parameters answered %d", w.Code)
872 }
873}
874
875// A page whose older page would start from more than MaxFrontier commits
876// links no older page, and says so: here a merge of more lines than that,
877// each still to show once the first page ends.
878func TestWideHistoryLinksNoOlderPage(t *testing.T) {
879 h := newHarness(t)
880 tip, bundle := h.lines(MaxFrontier+1, 2)
881 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
882 page := h.page("/app/source/log/" + tip)
883 if n := len(logged.FindAllString(page, -1)); n != LogPage {
884 t.Errorf("the page shows %d commits", n)
885 }
886 if strings.Contains(page, ">Older<") || !strings.Contains(page, "The older history runs along more lines at once than a page links.") {
887 t.Error("a page whose older page would start from more than MaxFrontier commits does not say so")
888 }
889}
890
891// A source request's git commands have a bound of their own, far within
892// the request's time: a git that does not finish is stopped once it
893// passes, and the request answers 503 and gives back its git slot. The
894// failure is logged.
895func TestSourceGitHasItsOwnBound(t *testing.T) {
896 h := newHarness(t)
897 real, err := exec.LookPath(export.GitProgram)
898 if err != nil {
899 t.Fatal(err)
900 }
901 if real, err = filepath.Abs(real); err != nil {
902 t.Fatal(err)
903 }
904 slow := filepath.Join(t.TempDir(), "git")
905 script := "#!/bin/sh\nfor a; do [ \"$a\" = ls-tree ] && exec sleep 60; done\nexec '" + real + "' \"$@\"\n"
906 if err := os.WriteFile(slow, []byte(script), 0o755); err != nil {
907 t.Fatal(err)
908 }
909 program := export.GitProgram
910 export.GitProgram = slow
911 t.Cleanup(func() { export.GitProgram = program })
912 var logged []error
913 var mu sync.Mutex
914 h.srv.log = func(err error) { mu.Lock(); logged = append(logged, err); mu.Unlock() }
915 h.srv.gitTime = 300 * time.Millisecond
916
917 start := time.Now()
918 w := h.get("/app/source/tree/" + h.tip() + "/")
919 if took := time.Since(start); w.Code != http.StatusServiceUnavailable || took > 5*time.Second {
920 t.Errorf("a source request whose git does not finish answered %d after %v", w.Code, took)
921 }
922 if len(h.srv.slots) != 0 {
923 t.Errorf("the request holds %d git slots once it answered", len(h.srv.slots))
924 }
925 mu.Lock()
926 defer mu.Unlock()
927 if len(logged) != 1 || !strings.Contains(logged[0].Error(), "the request held its git slot past 300ms") {
928 t.Errorf("the server logged %v", logged)
929 }
930 if w := h.get("/app/knots/oc-a000002"); w.Code != http.StatusOK {
931 t.Errorf("a knot answered %d", w.Code)
932 }
933}
934
935// A source request's bound on its git slot runs from when it takes the
936// slot, and covers its wait for its generation's export to be read. A
937// source request whose export is read slowly answers 503 once the bound
938// passes, gives back its slot, and is logged, while a request for the
939// plan, which holds no slot, waits on for the same read and is served.
940func TestGitSlotBoundCoversTheLoad(t *testing.T) {
941 h := newHarness(t)
942 var mu sync.Mutex
943 var logged []error
944 h.srv.log = func(err error) { mu.Lock(); logged = append(logged, err); mu.Unlock() }
945 h.srv.gitTime = 300 * time.Millisecond
946 hold := make(chan struct{})
947 h.srv.loading = func(export.Generation) { <-hold }
948
949 plan := make(chan *httptest.ResponseRecorder, 1)
950 go func() {
951 w := httptest.NewRecorder()
952 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
953 plan <- w
954 }()
955 eventually(t, "the plan waits for the export to be read", func() bool { return len(h.srv.loaders) == 1 })
956 start := time.Now()
957 w := h.get("/app/source/tree/" + h.tip() + "/")
958 if took := time.Since(start); w.Code != http.StatusServiceUnavailable || took > 5*time.Second {
959 t.Errorf("a source request whose export is read slowly answered %d after %v", w.Code, took)
960 }
961 if len(h.srv.slots) != 0 {
962 t.Errorf("the request holds %d git slots once it answered", len(h.srv.slots))
963 }
964 mu.Lock()
965 if len(logged) != 1 || !strings.Contains(logged[0].Error(), "the request held its git slot past 300ms") ||
966 !strings.Contains(logged[0].Error(), "export to be read") {
967 t.Errorf("the server logged %v", logged)
968 }
969 mu.Unlock()
970
971 close(hold)
972 select {
973 case w := <-plan:
974 if w.Code != http.StatusOK {
975 t.Errorf("the plan answered %d once its export was read", w.Code)
976 }
977 case <-time.After(10 * time.Second):
978 t.Fatal("the plan was not served once its export was read")
979 }
980 h.page("/app/source/tree/" + h.tip() + "/")
981}
982
983// A source request gives back its git slot before it renders its page, so
984// a page that renders slowly holds no slot, and is not held to the bound
985// on holding one. While one renders, past that bound, another source
986// request is served, and the first is served in full once it renders.
987func TestRenderingHoldsNoGitSlot(t *testing.T) {
988 h := newHarness(t)
989 h.page("/")
990 h.srv.gitTime = 300 * time.Millisecond
991 rendering, hold := make(chan struct{}), make(chan struct{})
992 var first atomic.Bool
993 h.srv.rendering = func(name string) {
994 if name == "tree" && first.CompareAndSwap(false, true) {
995 close(rendering)
996 <-hold
997 }
998 }
999
1000 served := make(chan *httptest.ResponseRecorder, 1)
1001 go func() {
1002 w := httptest.NewRecorder()
1003 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/source/tree/"+h.tip()+"/", nil))
1004 served <- w
1005 }()
1006 select {
1007 case <-rendering:
1008 case <-time.After(10 * time.Second):
1009 t.Fatal("the source request did not render")
1010 }
1011 if len(h.srv.slots) != 0 {
1012 t.Errorf("a source request holds %d git slots while it renders", len(h.srv.slots))
1013 }
1014 h.page("/app/source/blob/" + h.tip() + "/docs/guide.md")
1015 time.Sleep(2 * h.srv.gitTime)
1016 close(hold)
1017 select {
1018 case w := <-served:
1019 if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "guide.md") {
1020 t.Errorf("a source request that rendered past the bound on its slot answered %d", w.Code)
1021 }
1022 case <-time.After(10 * time.Second):
1023 t.Fatal("the source request was not served once it rendered")
1024 }
1025}
1026
1027// A SHA-256 project's commits are served by their 64 hex digits alone.
1028// The first 40 of them, which git would read as an abbreviation, answer
1029// 404 on every source route, so each page has one address.
1030func TestSHA256CommitIDs(t *testing.T) {
1031 h := newHarness(t)
1032 repo := filepath.Join(t.TempDir(), "app.git")
1033 git(t, repo, nil, "init", "--quiet", "--bare", "--template=", "--initial-branch=main", "--object-format=sha256")
1034 readme := "# app\n\nA SHA-256 repository.\n"
1035 who := "Example Author <author@example.org> 1791190800 +0000"
1036 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",
1037 who, who, len(readme), readme)
1038 git(t, repo, []byte(stream), "fast-import", "--quiet")
1039 tip := git(t, repo, nil, "rev-parse", export.MainRef)
1040 if len(tip) != 64 {
1041 t.Fatalf("the tip is %q", tip)
1042 }
1043 bundle := filepath.Join(t.TempDir(), "app.bundle")
1044 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
1045 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1046
1047 for _, route := range []string{"/app/source/tree/%s/", "/app/source/blob/%s/README.md", "/app/source/log/%s"} {
1048 if page := h.page(fmt.Sprintf(route, tip)); !strings.Contains(page, tip[:12]) {
1049 t.Errorf("%s does not name the commit", fmt.Sprintf(route, tip))
1050 }
1051 if w := h.get(fmt.Sprintf(route, tip[:40])); w.Code != http.StatusNotFound {
1052 t.Errorf("%s answered %d", fmt.Sprintf(route, tip[:40]), w.Code)
1053 }
1054 }
1055 if w := h.get("/app/source/"); w.Header().Get("Location") != "/app/source/tree/"+tip+"/" {
1056 t.Errorf("/app/source/ redirects to %q", w.Header().Get("Location"))
1057 }
1058}
1059
1060// A file of exactly MaxFile bytes of newlines is shown to MaxLines lines,
1061// and its page says where it stops. A README longer than a page shows is
1062// shown in part.
1063func TestLongFileIsShownInPart(t *testing.T) {
1064 h := newHarness(t)
1065 tip, bundle := h.commitMain("app: long files\n",
1066 file{"100644", "newlines.txt", strings.Repeat("\n", MaxFile)},
1067 file{"100644", "long/README.md", strings.Repeat("a line of the README\n", 2*MaxLines)},
1068 file{"100644", "wide.txt", strings.Repeat("<", MaxFile)},
1069 )
1070 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1071
1072 page := h.page("/app/source/blob/" + tip + "/newlines.txt")
1073 last := fmt.Sprintf(`id="L%d"`, MaxLines)
1074 if !strings.Contains(page, last) || strings.Contains(page, fmt.Sprintf(`id="L%d"`, MaxLines+1)) {
1075 t.Errorf("the file of newlines is not shown to line %d", MaxLines)
1076 }
1077 if want := fmt.Sprintf("The page stops at line %d of %d.", MaxLines, MaxFile); !strings.Contains(page, want) {
1078 t.Errorf("the page does not say %q", want)
1079 }
1080 if len(page) > MaxShown {
1081 t.Errorf("the page of a file of newlines is %d bytes, past MaxShown", len(page))
1082 }
1083
1084 // One line of MaxFile characters that each escape to four bytes is
1085 // cut where MaxShown is reached.
1086 page = h.page("/app/source/blob/" + tip + "/wide.txt")
1087 if !strings.Contains(page, "The page stops at line 1 of 1.") || len(page) > MaxShown+64<<10 {
1088 t.Errorf("the page of one wide line is %d bytes", len(page))
1089 }
1090
1091 page = h.page("/app/source/tree/" + tip + "/long/")
1092 if !strings.Contains(page, "This README is longer than a page shows, and only its start is shown.") {
1093 t.Error("the long README is not marked as shown in part")
1094 }
1095 if n := strings.Count(page, "a line of the README"); n != MaxLines {
1096 t.Errorf("the long README shows %d lines, not %d", n, MaxLines)
1097 }
1098}
1099
1100// A chain of knots as deep as the graph's knot limit allows renders its
1101// milestone to MaxPlanDepth levels, counts every knot under it, and
1102// names MaxPlanDepth parents in the deepest knot's trail. The plan page's
1103// structure is built once for the generation. Siblings that block one
1104// another in a cycle share the last stage of their path.
1105func TestDeepPlan(t *testing.T) {
1106 h := newHarness(t)
1107 var chain []string
1108 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
1109 p := &e.Projects[0]
1110 for i := range knot.MaxKnots - len(p.Knots) - 3 {
1111 id := fmt.Sprintf("oc-c%06x", i)
1112 k := export.Knot{ID: id, Type: "outcome", Status: "open", Active: true, State: "ready",
1113 Title: fmt.Sprintf("Level %d of the chain", i), Created: "2026-10-01", CreatedBy: "operator"}
1114 if i == 0 {
1115 p.Roots = append(p.Roots, id)
1116 } else {
1117 k.Parent = chain[i-1]
1118 p.Knots[len(p.Knots)-1].Children = []string{id}
1119 }
1120 chain = append(chain, id)
1121 p.Knots = append(p.Knots, k)
1122 }
1123 // Under the first link, a path whose two last siblings wait on
1124 // each other.
1125 free, a, b := "oc-d000001", "oc-d000002", "oc-d000003"
1126 for _, k := range []export.Knot{
1127 {ID: free, BlockedBy: []string{}},
1128 {ID: a, BlockedBy: []string{free, b}},
1129 {ID: b, BlockedBy: []string{a}},
1130 } {
1131 k.Type, k.Status, k.State, k.Title, k.Parent = "outcome", "open", "blocked", "Sibling "+k.ID, chain[0]
1132 p.Knots = append(p.Knots, k)
1133 }
1134 for i := range p.Knots {
1135 if p.Knots[i].ID == chain[0] {
1136 p.Knots[i].Children = append(p.Knots[i].Children, free, a, b)
1137 }
1138 }
1139 })
1140
1141 page := h.page("/")
1142 if want := fmt.Sprintf("%d of %d done", 0, len(chain)-1+3); !strings.Contains(page, want) {
1143 t.Errorf("the chain's milestone does not count every knot under it as %q", want)
1144 }
1145 if !strings.Contains(page, `href="/app/knots/`+chain[MaxPlanDepth]+`"`) || strings.Contains(page, `href="/app/knots/`+chain[MaxPlanDepth+1]+`"`) {
1146 t.Errorf("the chain's tree is not shown to %d levels", MaxPlanDepth)
1147 }
1148 if n := strings.Count(page, ">more on its page<"); n != 1 {
1149 t.Errorf("%d rows say there is more on their page; the chain's deepest shown row does", n)
1150 }
1151 if len(page) > 256<<10 {
1152 t.Errorf("the plan page is %d bytes", len(page))
1153 }
1154 paths := section(t, page, `id="paths-h"`, `id="ms-h"`)
1155 stage := regexp.MustCompile(`<span class="stage-num">(\d+)</span><ul class="plain">(.*?)</ul>`)
1156 var stages []string
1157 for _, m := range stage.FindAllStringSubmatch(paths, -1) {
1158 if strings.Contains(m[2], "Sibling") {
1159 var ids []string
1160 for _, id := range regexp.MustCompile(`"mono muted">(oc-d00000\d)<`).FindAllStringSubmatch(m[2], -1) {
1161 ids = append(ids, id[1])
1162 }
1163 stages = append(stages, m[1]+":"+strings.Join(ids, ","))
1164 }
1165 }
1166 if got := strings.Join(stages, " "); got != "1:oc-d000001 2:oc-d000002,oc-d000003" {
1167 t.Errorf("the siblings' path has stages %q", got)
1168 }
1169
1170 h.srv.mu.Lock()
1171 plan := h.srv.cached.idx.plan
1172 h.srv.mu.Unlock()
1173 h.page("/")
1174 h.srv.mu.Lock()
1175 again := h.srv.cached.idx.plan
1176 h.srv.mu.Unlock()
1177 if plan != again {
1178 t.Error("the plan page's structure was built again for the same generation")
1179 }
1180
1181 deepest := chain[len(chain)-1]
1182 page = h.page("/app/knots/" + deepest)
1183 trail := section(t, page, `<nav class="trail"`, `</nav>`)
1184 if n := strings.Count(trail, `<a href="/app/knots/`); n != MaxPlanDepth || !strings.Contains(trail, "<span>…</span>") {
1185 t.Errorf("the deepest knot's trail names %d parents, or does not mark those above them", n)
1186 }
1187 if !strings.Contains(trail, chain[len(chain)-2]) || strings.Contains(trail, `"/app/knots/`+chain[len(chain)-2-MaxPlanDepth]+`"`) {
1188 t.Error("the trail does not name the nearest parents alone")
1189 }
1190}
1191
1192// Every response carries the strict policy, and the policy admits the
1193// page's one inline stylesheet and one inline script by their hashes and
1194// nothing from another origin.
1195func TestEveryResponseCarriesTheCSP(t *testing.T) {
1196 h := newHarness(t)
1197 for _, c := range []struct{ method, target string }{
1198 {"GET", "/"},
1199 {"GET", "/app/knots/oc-a000002"},
1200 {"GET", "/app/source/"},
1201 {"GET", "/app/source/tree/" + h.tip() + "/"},
1202 {"GET", "/app/source/blob/" + h.tip() + "/README.md"},
1203 {"GET", "/no/such/page"},
1204 {"POST", "/"},
1205 {"HEAD", "/"},
1206 } {
1207 w := h.do(c.method, c.target)
1208 got := w.Header().Get("Content-Security-Policy")
1209 if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" {
1210 t.Errorf("%s %s answered with policy %q", c.method, c.target, got)
1211 }
1212 }
1213 for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} {
1214 if !strings.Contains(csp, directive) {
1215 t.Errorf("the policy lacks %s", directive)
1216 }
1217 }
1218 for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} {
1219 if strings.Contains(csp, loose) {
1220 t.Errorf("the policy holds %q", loose)
1221 }
1222 }
1223
1224 page := h.page("/")
1225 inline := func(tag string) string {
1226 t.Helper()
1227 m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1)
1228 if len(m) != 1 || strings.Count(page, "<"+tag) != 1 {
1229 t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag)
1230 }
1231 sum := sha256.Sum256([]byte(m[0][1]))
1232 return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
1233 }
1234 if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") {
1235 t.Errorf("the policy does not admit the page's script, %s", hash)
1236 }
1237 if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") {
1238 t.Errorf("the policy does not admit the page's stylesheet, %s", hash)
1239 }
1240 for _, external := range []string{"<link", " src=", "@import", "url("} {
1241 if strings.Contains(page, external) {
1242 t.Errorf("the plan page holds %q", external)
1243 }
1244 }
1245}
1246
1247// A request serves everything from the generation it opened, though
1248// another activates while it runs, and that generation outlives the
1249// activation until the request releases it.
1250func TestARequestKeepsItsGeneration(t *testing.T) {
1251 h := newHarness(t)
1252 paused, resume := make(chan export.Generation), make(chan struct{})
1253 var once sync.Once
1254 h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) }
1255 served := make(chan *httptest.ResponseRecorder)
1256 go func() {
1257 w := httptest.NewRecorder()
1258 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/knots/oc-a000001", nil))
1259 served <- w
1260 }()
1261 old := <-paused
1262
1263 next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1264 if next.Sequence == old.Sequence {
1265 t.Fatal("the publish did not activate a new generation")
1266 }
1267 if _, err := os.Stat(old.Dir); err != nil {
1268 t.Fatalf("the generation a request holds was deleted: %v", err)
1269 }
1270 close(resume)
1271 w := <-served
1272 if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app&#39;s plan") || strings.Contains(body, "second plan") {
1273 t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body)
1274 }
1275 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the second plan") {
1276 t.Error("the next request does not serve the new generation")
1277 }
1278
1279 // Released, the old generation goes with the next activation.
1280 h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1281 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1282 t.Errorf("the released generation is still on disk: %v", err)
1283 }
1284}
1285
1286// eventually waits up to ten seconds for cond to hold.
1287func eventually(t *testing.T, what string, cond func() bool) {
1288 t.Helper()
1289 for deadline := time.Now().Add(10 * time.Second); !cond(); time.Sleep(time.Millisecond) {
1290 if time.Now().After(deadline) {
1291 t.Fatalf("timed out waiting until %s", what)
1292 }
1293 }
1294}
1295
1296// renamed changes the title of the fixture's first knot.
1297func renamed(title string) func(*export.Export) {
1298 return func(e *export.Export) { e.Projects[0].Knots[0].Title = title }
1299}
1300
1301// Requests that wait for a generation together read its export once.
1302// While it is read, a newer generation is read on its own, and at most
1303// MaxLoads exports are read at once. A request whose load ends after a
1304// newer generation was activated waits for that one, so every request is
1305// served the generation active when its snapshot is ready, and an older
1306// read that finishes last does not displace the newest snapshot.
1307func TestExportLoadsCoalesce(t *testing.T) {
1308 h := newHarness(t)
1309 var mu sync.Mutex
1310 loads := map[int64]int{}
1311 holds := map[int64]chan struct{}{}
1312 hold := func(g export.Generation) chan struct{} {
1313 mu.Lock()
1314 defer mu.Unlock()
1315 if holds[g.Sequence] == nil {
1316 holds[g.Sequence] = make(chan struct{})
1317 }
1318 return holds[g.Sequence]
1319 }
1320 h.srv.loading = func(g export.Generation) {
1321 mu.Lock()
1322 loads[g.Sequence]++
1323 mu.Unlock()
1324 <-hold(g)
1325 }
1326 loaded := func(g export.Generation) int {
1327 mu.Lock()
1328 defer mu.Unlock()
1329 return loads[g.Sequence]
1330 }
1331 var opens atomic.Int32
1332 h.srv.opened = func(export.Generation) { opens.Add(1) }
1333 get := func(n int) chan *httptest.ResponseRecorder {
1334 served := make(chan *httptest.ResponseRecorder, n)
1335 for range n {
1336 go func() {
1337 w := httptest.NewRecorder()
1338 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/knots/oc-a000001", nil))
1339 served <- w
1340 }()
1341 }
1342 return served
1343 }
1344 expect := func(served chan *httptest.ResponseRecorder, n int, title string) {
1345 t.Helper()
1346 for range n {
1347 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
1348 t.Errorf("a request answered %d, not with %q", w.Code, title)
1349 }
1350 }
1351 }
1352 waiting := func(n int) func() bool { return func() bool { return len(h.srv.loadWaiting) == n } }
1353
1354 first := h.active()
1355 firstServed := get(10)
1356 eventually(t, "ten requests wait for the first generation's read", func() bool {
1357 return loaded(first) == 1 && len(h.srv.loadWaiting) == 10
1358 })
1359 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1360 secondServed := get(1)
1361 eventually(t, "the second generation is read", func() bool { return loaded(second) == 1 })
1362
1363 // Both loaders are taken, so the third generation waits for one.
1364 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1365 thirdServed := get(1)
1366 eventually(t, "a request waits for the third generation", waiting(12))
1367 time.Sleep(20 * time.Millisecond)
1368 if n := loaded(third); n != 0 {
1369 t.Errorf("a third export was read while %d were", MaxLoads)
1370 }
1371 if n := opens.Load(); n != 0 {
1372 t.Errorf("%d requests opened a generation while they waited for its read", n)
1373 }
1374
1375 // The second read ends, and its request finds the third generation
1376 // active, and waits for that read with the third's request.
1377 close(hold(second))
1378 eventually(t, "the third generation is read", func() bool { return loaded(third) == 1 })
1379 close(hold(third))
1380 expect(secondServed, 1, "Readers browse the third plan")
1381 expect(thirdServed, 1, "Readers browse the third plan")
1382 close(hold(first))
1383 expect(firstServed, 10, "Readers browse the third plan")
1384
1385 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the third plan") {
1386 t.Error("the first generation's read displaced the third's")
1387 }
1388 for _, g := range []export.Generation{first, second, third} {
1389 if n := loaded(g); n != 1 {
1390 t.Errorf("generation %d's export was read %d times", g.Sequence, n)
1391 }
1392 }
1393}
1394
1395// Source requests past MaxGit wait, MaxWaiting of them, and one more
1396// answers 503 at once. A waiting request holds no generation, so an
1397// activation while the server is saturated deletes the old generation,
1398// and every waiting request serves the new one. A request's time runs
1399// from its arrival, so one that waits past it answers 503.
1400func TestSourceAdmission(t *testing.T) {
1401 h := newHarness(t)
1402 // The requests that hold the slots wait for the test, not for git, so
1403 // the bound on holding a slot is no part of this test.
1404 h.srv.gitTime = time.Hour
1405 var admitted atomic.Int32
1406 release := make(chan struct{})
1407 h.srv.admitted = func() {
1408 admitted.Add(1)
1409 <-release
1410 }
1411 target := "/app/source/tree/" + h.tip() + "/"
1412 get := func(n int) chan *httptest.ResponseRecorder {
1413 served := make(chan *httptest.ResponseRecorder, n)
1414 for range n {
1415 go func() {
1416 w := httptest.NewRecorder()
1417 h.srv.ServeHTTP(w, httptest.NewRequest("GET", target, nil))
1418 served <- w
1419 }()
1420 }
1421 return served
1422 }
1423
1424 old := h.active()
1425 served := get(MaxGit + MaxWaiting)
1426 eventually(t, "every slot is taken and MaxWaiting requests wait", func() bool {
1427 return admitted.Load() == MaxGit && len(h.srv.waiting) == MaxWaiting
1428 })
1429 if w := h.get(target); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1430 t.Errorf("a source request past MaxWaiting answered %d, Retry-After %q", w.Code, w.Header().Get("Retry-After"))
1431 }
1432 h.page("/") // a page that runs no git is served still
1433
1434 tip, bundle := h.commitMain("app: a commit while the server is saturated\n", file{"100644", "saturated.txt", "saturated\n"})
1435 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1436 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1437 t.Errorf("a generation no request had opened outlived the activation: %v", err)
1438 }
1439 close(release)
1440 for range MaxGit + MaxWaiting {
1441 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "/app/source/tree/"+tip+"/") {
1442 t.Errorf("a waiting request answered %d, not from the new generation", w.Code)
1443 }
1444 }
1445
1446 // A request that waits past its time answers 503. Those that held
1447 // the slots meanwhile ran out of time too.
1448 h.srv.timeout = 200 * time.Millisecond
1449 h.srv.log = func(error) {}
1450 admitted.Store(0)
1451 release = make(chan struct{})
1452 held := get(MaxGit)
1453 eventually(t, "every slot is taken", func() bool { return admitted.Load() == MaxGit })
1454 start := time.Now()
1455 if w := h.get(target); w.Code != http.StatusServiceUnavailable {
1456 t.Errorf("a request that waited past its time answered %d", w.Code)
1457 }
1458 if waited := time.Since(start); waited > 5*time.Second {
1459 t.Errorf("a request waited %v past its time of 200ms", waited)
1460 }
1461 close(release)
1462 for range MaxGit {
1463 if w := <-held; w.Code != http.StatusServiceUnavailable {
1464 t.Errorf("a request that ran out of time answered %d", w.Code)
1465 }
1466 }
1467}
1468
1469// stallingListener accepts connections whose writes stall until release
1470// is closed, while stall is set. Each sends on stalled the first time one
1471// of its writes stalls.
1472type stallingListener struct {
1473 net.Listener
1474 stall atomic.Bool
1475 release chan struct{}
1476 stalled chan struct{}
1477}
1478
1479func (l *stallingListener) Accept() (net.Conn, error) {
1480 c, err := l.Listener.Accept()
1481 if err != nil || !l.stall.Load() {
1482 return c, err
1483 }
1484 return &stallingConn{Conn: c, l: l}, nil
1485}
1486
1487type stallingConn struct {
1488 net.Conn
1489 l *stallingListener
1490 once sync.Once
1491}
1492
1493func (c *stallingConn) Write(p []byte) (int, error) {
1494 c.once.Do(func() { c.l.stalled <- struct{}{} })
1495 <-c.l.release
1496 return c.Conn.Write(p)
1497}
1498
1499// Readers that never read their responses hold no git slot and no
1500// generation: more of them than MaxGit and MaxWaiting together are
1501// stalled writing, and a new reader is still served, and an activation
1502// deletes the generation they were served from.
1503func TestSlowReadersHoldNothing(t *testing.T) {
1504 h := newHarness(t)
1505 ln, err := net.Listen("tcp", "127.0.0.1:0")
1506 if err != nil {
1507 t.Fatal(err)
1508 }
1509 n := MaxGit + MaxWaiting + 4
1510 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
1511 sl.stall.Store(true)
1512 srv := &http.Server{Handler: h.srv}
1513 go srv.Serve(sl)
1514 var conns []net.Conn
1515 defer func() {
1516 close(sl.release)
1517 for _, c := range conns {
1518 c.Close()
1519 }
1520 srv.Close()
1521 }()
1522
1523 old := h.active()
1524 target := "/app/source/blob/" + h.tip() + "/docs/guide.md"
1525 for range n {
1526 c, err := net.Dial("tcp", ln.Addr().String())
1527 if err != nil {
1528 t.Fatal(err)
1529 }
1530 conns = append(conns, c)
1531 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
1532 }
1533 for i := range n {
1534 select {
1535 case <-sl.stalled:
1536 case <-time.After(10 * time.Second):
1537 t.Fatalf("%d of %d slow readers' responses were written; the rest wait", i, n)
1538 }
1539 }
1540 sl.stall.Store(false)
1541 if len(h.srv.slots) != 0 || len(h.srv.waiting) != 0 {
1542 t.Errorf("slow readers hold %d git slots, and %d requests wait", len(h.srv.slots), len(h.srv.waiting))
1543 }
1544
1545 client := &http.Client{Timeout: 10 * time.Second}
1546 resp, err := client.Get("http://" + ln.Addr().String() + target)
1547 if err != nil {
1548 t.Fatal(err)
1549 }
1550 resp.Body.Close()
1551 if resp.StatusCode != http.StatusOK {
1552 t.Errorf("a new reader answered %d while slow readers stall", resp.StatusCode)
1553 }
1554 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(*export.Export) {})
1555 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1556 t.Errorf("the generation slow readers were served from outlived the activation: %v", err)
1557 }
1558}
1559
1560// Before the first activation the server says nothing is published, and
1561// it answers GET and HEAD alone.
1562func TestNothingPublishedAndMethods(t *testing.T) {
1563 store, err := export.OpenStore(t.TempDir(), nil)
1564 if err != nil {
1565 t.Fatal(err)
1566 }
1567 srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }})
1568 w := httptest.NewRecorder()
1569 srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
1570 if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") {
1571 t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body)
1572 }
1573
1574 h := newHarness(t)
1575 for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} {
1576 w := h.do(method, "/")
1577 if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" {
1578 t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow"))
1579 }
1580 }
1581}
1582
1583// tooLarge checks that GET target answers with the one short page that
1584// says a page is too large.
1585func (h *harness) tooLarge(target string) {
1586 h.t.Helper()
1587 w := h.get(target)
1588 if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) {
1589 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())
1590 }
1591 if n, _ := h.srv.holding(); n != 0 {
1592 h.t.Errorf("GET %s kept %d pieces of the budget", target, n)
1593 }
1594}
1595
1596// A response's body is at most MaxResponse bytes. A page that would pass
1597// the bound answers with the one short page that says it is too large,
1598// and the failure is logged: a knot whose body passes MaxResponse, and,
1599// under a smaller bound, a file, a directory, a page of history and the
1600// plan page. A page within the bound is served on each route.
1601func TestPageTooLarge(t *testing.T) {
1602 h := newHarness(t)
1603 var logged []string
1604 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
1605 files := []file{{"100644", "wide.txt", strings.Repeat("<", 16<<10)}}
1606 for i := range 32 {
1607 files = append(files, file{"100644", fmt.Sprintf("wide/%02d-%s", i, strings.Repeat("n", 1000)), "x\n"})
1608 }
1609 h.commitMain("app: a wide file and a wide directory\n", files...)
1610 var tip, bundle string
1611 for i := range 8 {
1612 tip, bundle = h.commitMain(fmt.Sprintf("%d %s\n", i, strings.Repeat(`"`, maxLogText)))
1613 }
1614 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
1615 p := &e.Projects[0]
1616 p.SourceTip = tip
1617 p.Knots[0].Body = strings.Repeat("a", MaxResponse)
1618 for i := range 100 {
1619 p.Knots = append(p.Knots, export.Knot{ID: fmt.Sprintf("oc-e%06x", i), Type: "outcome", Status: "open",
1620 Active: true, State: "ready", Title: strings.Repeat(`"`, knot.MaxTitle), Created: "2026-10-01", CreatedBy: "operator"})
1621 }
1622 })
1623
1624 h.tooLarge("/app/knots/" + h.f.Export.Projects[0].Knots[0].ID)
1625 h.page("/app/knots/oc-a000002")
1626
1627 h.srv.maxResponse = 32 << 10
1628 at := "/app/source/blob/" + tip + "/"
1629 h.tooLarge(at + "wide.txt")
1630 h.page(at + "docs/guide.md")
1631 at = "/app/source/tree/" + tip + "/"
1632 h.tooLarge(at + "wide/")
1633 h.page(at + "docs/")
1634 h.tooLarge("/app/source/log/" + tip)
1635 h.page("/app/source/log/" + git(t, h.f.Repos["app"], nil, "rev-parse", tip+"~8"))
1636 h.tooLarge("/")
1637
1638 if len(logged) != 5 {
1639 t.Errorf("%d failures were logged for 5 pages too large: %q", len(logged), logged)
1640 }
1641 for _, l := range logged {
1642 if !strings.Contains(l, "larger than") {
1643 t.Errorf("the server logged %q", l)
1644 }
1645 }
1646 if len(tooLargePage) > 16<<10 {
1647 t.Errorf("the page that says a page is too large is %d bytes", len(tooLargePage))
1648 }
1649}
1650
1651// holding is how many pieces of the budget responses hold, and how many
1652// of those the large budget counts.
1653func (s *Server) holding() (held, large int) {
1654 s.pieces.Lock()
1655 defer s.pieces.Unlock()
1656 return s.held, s.large
1657}
1658
1659// Rendered responses share a budget of MaxBuffered bytes, which each
1660// holds from when it starts rendering until it is written. Responses
1661// larger than SmallPage hold at most MaxLarge of it between them, their
1662// first SmallPage bytes counted. Readers that never read large pages ask
1663// for more than the whole budget, in pages of three sizes: one piece past
1664// SmallPage, 1 MiB, and 4 MiB. Without the first SmallPage bytes counted,
1665// 64 readers of the 1 MiB page would hold all of the budget. Once the
1666// readers' pages hold what fits in MaxLarge, a large page answers 503 at
1667// once, while small pages still render: the plan, a knot and a
1668// directory. The server's heap grows by no more than the budget, and the
1669// budget is whole again once the readers read.
1670func TestSlowReadersShareTheBudget(t *testing.T) {
1671 for _, pieces := range []int{smallPieces + 1, 16, 64} {
1672 t.Run(fmt.Sprintf("%d pieces", pieces), func(t *testing.T) { slowReadersOfPages(t, pieces) })
1673 }
1674}
1675
1676// slowReadersOfPages runs TestSlowReadersShareTheBudget with large pages
1677// of the number of pieces given.
1678func slowReadersOfPages(t *testing.T, pieces int) {
1679 h := newHarness(t)
1680 target := "/app/knots/" + h.f.Export.Projects[0].Knots[0].ID
1681 body := func(at time.Duration, text string) {
1682 h.publish(exporttest.SignedAt.Add(at), nil, func(e *export.Export) { e.Projects[0].Knots[0].Body = text })
1683 }
1684 body(time.Minute, "x")
1685 rest := len(h.page(target)) - 1
1686 body(2*time.Minute, strings.Repeat("a line of a long body\n", (pieces*pieceSize-rest-1024)/22))
1687 size := len(h.page(target))
1688 if got := (size + pieceSize - 1) / pieceSize; got != pieces {
1689 t.Fatalf("the large page takes %d pieces, not %d", got, pieces)
1690 }
1691 fit := largePieces / pieces
1692 n := MaxBuffered/size + 2
1693
1694 ln, err := net.Listen("tcp", "127.0.0.1:0")
1695 if err != nil {
1696 t.Fatal(err)
1697 }
1698 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
1699 sl.stall.Store(true)
1700 srv := &http.Server{Handler: h.srv}
1701 go srv.Serve(sl)
1702 var conns []net.Conn
1703 released := false
1704 defer func() {
1705 if !released {
1706 close(sl.release)
1707 }
1708 for _, c := range conns {
1709 c.Close()
1710 }
1711 srv.Close()
1712 }()
1713
1714 var before runtime.MemStats
1715 runtime.GC()
1716 runtime.ReadMemStats(&before)
1717 // One reader at a time, each stalled before the next asks, so the
1718 // readers that fill the budget are the first fit of them.
1719 for i := range n {
1720 c, err := net.Dial("tcp", ln.Addr().String())
1721 if err != nil {
1722 t.Fatal(err)
1723 }
1724 conns = append(conns, c)
1725 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
1726 select {
1727 case <-sl.stalled:
1728 case <-time.After(10 * time.Second):
1729 t.Fatalf("reader %d of %d was not answered", i+1, n)
1730 }
1731 }
1732 sl.stall.Store(false)
1733 var after runtime.MemStats
1734 runtime.GC()
1735 runtime.ReadMemStats(&after)
1736 if held, large := h.srv.holding(); held != fit*pieces || large != fit*pieces {
1737 t.Errorf("slow readers hold %d pieces, %d of them counted as large; %d pages of %d pieces fit", held, large, fit, pieces)
1738 }
1739 if grew := int64(after.HeapAlloc) - int64(before.HeapAlloc); grew > MaxBuffered+8<<20 {
1740 t.Errorf("%d slow readers of %d bytes each grew the heap by %d bytes, past MaxBuffered", n, size, grew)
1741 }
1742
1743 client := &http.Client{Timeout: 10 * time.Second}
1744 get := func(target string) (int, string) {
1745 t.Helper()
1746 resp, err := client.Get("http://" + ln.Addr().String() + target)
1747 if err != nil {
1748 t.Fatal(err)
1749 }
1750 defer resp.Body.Close()
1751 io.Copy(io.Discard, resp.Body)
1752 return resp.StatusCode, resp.Header.Get("Retry-After")
1753 }
1754 if code, retry := get(target); code != http.StatusServiceUnavailable || retry == "" {
1755 t.Errorf("a page the budget has no room for answered %d, Retry-After %q", code, retry)
1756 }
1757 for _, small := range []string{"/", "/app/knots/oc-a000002", "/app/source/tree/" + h.tip() + "/"} {
1758 if code, _ := get(small); code != http.StatusOK {
1759 t.Errorf("the small page %s answered %d while slow readers hold MaxLarge", small, code)
1760 }
1761 }
1762
1763 close(sl.release)
1764 released = true
1765 codes := map[int]int{}
1766 for _, c := range conns {
1767 c.SetReadDeadline(time.Now().Add(10 * time.Second))
1768 resp, err := http.ReadResponse(bufio.NewReader(c), nil)
1769 if err != nil {
1770 t.Fatal(err)
1771 }
1772 read, err := io.Copy(io.Discard, resp.Body)
1773 resp.Body.Close()
1774 if err != nil || resp.StatusCode == http.StatusOK && read != int64(size) {
1775 t.Errorf("a slow reader read %d bytes of %d: %v", read, size, err)
1776 }
1777 codes[resp.StatusCode]++
1778 }
1779 if codes[http.StatusOK] != fit || codes[http.StatusServiceUnavailable] != n-fit {
1780 t.Errorf("of %d slow readers, %d were served and %d answered 503; %d pages fit the budget",
1781 n, codes[http.StatusOK], codes[http.StatusServiceUnavailable], fit)
1782 }
1783 eventually(t, "the budget is whole again", func() bool { held, _ := h.srv.holding(); return held == 0 })
1784}
1785
1786// A load starts only once a request that waits for it takes a loader
1787// slot. While MaxLoads loads run, a request for a newer generation waits
1788// for a slot, holding no generation, until its time runs out, whatever
1789// its route, or its reader goes away. Neither leaves a load behind.
1790func TestExportLoadWaitsEnd(t *testing.T) {
1791 h := newHarness(t)
1792 var mu sync.Mutex
1793 var logged []string
1794 h.srv.log = func(err error) {
1795 mu.Lock()
1796 defer mu.Unlock()
1797 logged = append(logged, err.Error())
1798 }
1799 loads := map[int64]int{}
1800 hold := make(chan struct{})
1801 h.srv.loading = func(g export.Generation) {
1802 mu.Lock()
1803 loads[g.Sequence]++
1804 mu.Unlock()
1805 <-hold
1806 }
1807 loaded := func(g export.Generation) int {
1808 mu.Lock()
1809 defer mu.Unlock()
1810 return loads[g.Sequence]
1811 }
1812 serve := func(r *http.Request) chan *httptest.ResponseRecorder {
1813 served := make(chan *httptest.ResponseRecorder, 1)
1814 go func() {
1815 w := httptest.NewRecorder()
1816 h.srv.ServeHTTP(w, r)
1817 served <- w
1818 }()
1819 return served
1820 }
1821 expect := func(served chan *httptest.ResponseRecorder, title string) {
1822 t.Helper()
1823 select {
1824 case w := <-served:
1825 if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
1826 t.Errorf("a request answered %d, not with %q", w.Code, title)
1827 }
1828 case <-time.After(10 * time.Second):
1829 t.Fatalf("a request was not answered with %q", title)
1830 }
1831 }
1832
1833 first := h.active()
1834 firstServed := serve(httptest.NewRequest("GET", "/", nil))
1835 eventually(t, "the first generation is read", func() bool { return loaded(first) == 1 })
1836 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1837 secondServed := serve(httptest.NewRequest("GET", "/", nil))
1838 eventually(t, "both loader slots are taken", func() bool { return loaded(second) == 1 })
1839
1840 // A request that runs no git runs out of time waiting, and answers
1841 // 503.
1842 h.srv.timeout = 200 * time.Millisecond
1843 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1844 select {
1845 case w := <-serve(httptest.NewRequest("GET", "/app/knots/oc-a000001", nil)):
1846 if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1847 t.Errorf("a request that waited past its time for a read answered %d", w.Code)
1848 }
1849 case <-time.After(10 * time.Second):
1850 t.Fatal("a request waits for a read past its time of 200ms")
1851 }
1852
1853 // A request whose reader goes away stops waiting, and answers
1854 // nothing.
1855 h.srv.timeout = time.Hour
1856 fourth := h.publish(exporttest.SignedAt.Add(3*time.Minute), nil, renamed("Readers browse the fourth plan"))
1857 ctx, cancel := context.WithCancel(context.Background())
1858 defer cancel()
1859 gone := serve(httptest.NewRequest("GET", "/", nil).WithContext(ctx))
1860 eventually(t, "a request waits for the fourth generation", func() bool { return len(h.srv.loadWaiting) == 3 })
1861 cancel()
1862 select {
1863 case w := <-gone:
1864 if w.Body.Len() != 0 {
1865 t.Errorf("a request whose reader went away answered %d", w.Code)
1866 }
1867 case <-time.After(10 * time.Second):
1868 t.Fatal("a request whose reader went away still waits")
1869 }
1870
1871 h.srv.mu.Lock()
1872 left := len(h.srv.loads)
1873 h.srv.mu.Unlock()
1874 if left != MaxLoads {
1875 t.Errorf("%d loads may be joined; only the %d that run are wanted", left, MaxLoads)
1876 }
1877 h.publish(exporttest.SignedAt.Add(4*time.Minute), nil, renamed("Readers browse the fifth plan"))
1878 for _, g := range []export.Generation{third, fourth} {
1879 if _, err := os.Stat(g.Dir); !os.IsNotExist(err) {
1880 t.Errorf("generation %d outlived an activation after its request gave up: %v", g.Sequence, err)
1881 }
1882 }
1883
1884 // The first two reads end, and their requests are served the newest
1885 // generation.
1886 close(hold)
1887 expect(firstServed, "Readers browse the fifth plan")
1888 expect(secondServed, "Readers browse the fifth plan")
1889 for _, g := range []export.Generation{third, fourth} {
1890 if n := loaded(g); n != 0 {
1891 t.Errorf("generation %d's export was read %d times after every request for it gave up", g.Sequence, n)
1892 }
1893 }
1894 mu.Lock()
1895 defer mu.Unlock()
1896 if len(logged) != 1 || !strings.Contains(logged[0], "deadline exceeded") {
1897 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
1898 }
1899}
1900
1901// A load that reads slowly does not hold the request that waits for it:
1902// the request answers 503 at its deadline. With no request left waiting,
1903// the load stops reading part way through the export, caches nothing, and
1904// gives back its generation, which the next activation deletes. A load
1905// that ends is kept, and the requests after it are served without another
1906// read.
1907func TestSlowLoadEndsWithItsRequests(t *testing.T) {
1908 h := newHarness(t)
1909 h.srv.timeout = 200 * time.Millisecond
1910 var mu sync.Mutex
1911 var logged []string
1912 h.srv.log = func(err error) {
1913 mu.Lock()
1914 defer mu.Unlock()
1915 logged = append(logged, err.Error())
1916 }
1917 var reads atomic.Int32
1918 h.srv.loading = func(export.Generation) { reads.Add(1) }
1919
1920 // The active generation's export.json becomes a pipe the test writes
1921 // a few bytes at a time, as a slow disk would give it: all of it
1922 // takes about 4 seconds, twenty times the request's time.
1923 old := h.active()
1924 data, err := os.ReadFile(old.ExportPath())
1925 if err != nil {
1926 t.Fatal(err)
1927 }
1928 if err := os.Remove(old.ExportPath()); err != nil {
1929 t.Fatal(err)
1930 }
1931 if err := syscall.Mkfifo(old.ExportPath(), 0o600); err != nil {
1932 t.Fatal(err)
1933 }
1934 piece := max(1, len(data)/200)
1935 wrote := make(chan error, 1)
1936 go func() {
1937 f, err := os.OpenFile(old.ExportPath(), os.O_WRONLY, 0)
1938 if err != nil {
1939 wrote <- err
1940 return
1941 }
1942 defer f.Close()
1943 for p := data; len(p) > 0; p = p[min(len(p), piece):] {
1944 if _, err := f.Write(p[:min(len(p), piece)]); err != nil {
1945 wrote <- err
1946 return
1947 }
1948 time.Sleep(20 * time.Millisecond)
1949 }
1950 wrote <- nil
1951 }()
1952
1953 start := time.Now()
1954 if w := h.get("/"); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1955 t.Errorf("a request whose load ran past its time answered %d", w.Code)
1956 }
1957 if waited := time.Since(start); waited > 2*time.Second {
1958 t.Errorf("a request waited %v for a slow load, past its time of 200ms", waited)
1959 }
1960 select {
1961 case err := <-wrote:
1962 if !errors.Is(err, syscall.EPIPE) {
1963 t.Errorf("the load read the whole export after its request gave up: the writer ended with %v", err)
1964 }
1965 case <-time.After(10 * time.Second):
1966 t.Fatal("the load still reads the export")
1967 }
1968 eventually(t, "the load ends", func() bool { return len(h.srv.loaders) == 0 })
1969 h.srv.mu.Lock()
1970 cached, loads := h.srv.cached, len(h.srv.loads)
1971 h.srv.mu.Unlock()
1972 if cached != nil || loads != 0 {
1973 t.Errorf("a load that stopped left a snapshot %v and %d loads", cached != nil, loads)
1974 }
1975 // The store reads the active export.json when it takes an upload.
1976 if err := os.Remove(old.ExportPath()); err != nil {
1977 t.Fatal(err)
1978 }
1979 if err := os.WriteFile(old.ExportPath(), data, 0o644); err != nil {
1980 t.Fatal(err)
1981 }
1982 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1983 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1984 t.Errorf("the generation a stopped load opened outlived an activation: %v", err)
1985 }
1986
1987 h.srv.timeout = requestTimeout
1988 for range 3 {
1989 if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the second plan") {
1990 t.Error("a request after the stopped load is not served the new generation")
1991 }
1992 }
1993 if n := reads.Load(); n != 2 {
1994 t.Errorf("exports were read %d times: once in part, and once for the new generation", n)
1995 }
1996 mu.Lock()
1997 defer mu.Unlock()
1998 if len(logged) != 1 || !strings.Contains(logged[0], "export to be read: context deadline exceeded") {
1999 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
2000 }
2001}
2002
2003// openFiles is the number of files the process holds open, and false
2004// where the system does not list them.
2005func openFiles(t *testing.T) (int, bool) {
2006 t.Helper()
2007 entries, err := os.ReadDir("/proc/self/fd")
2008 if err != nil {
2009 return 0, false
2010 }
2011 return len(entries), true
2012}
2013
2014// A flood of requests while a load runs: MaxLoadWaiting of them wait, and
2015// the rest answer 503 at once, unlogged. A waiting request holds no
2016// generation, so the goroutines and files the server holds stay within a
2017// bound however large the flood. Once the load ends, every request that
2018// waited is served from its one read.
2019func TestLoadFlood(t *testing.T) {
2020 h := newHarness(t)
2021 var reads atomic.Int32
2022 reading, hold := make(chan struct{}, 1), make(chan struct{})
2023 h.srv.loading = func(export.Generation) {
2024 reads.Add(1)
2025 reading <- struct{}{}
2026 <-hold
2027 }
2028 get := func(n int) chan *httptest.ResponseRecorder {
2029 served := make(chan *httptest.ResponseRecorder, n)
2030 for range n {
2031 go func() {
2032 w := httptest.NewRecorder()
2033 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
2034 served <- w
2035 }()
2036 }
2037 return served
2038 }
2039
2040 first := get(1)
2041 select {
2042 case <-reading:
2043 case <-time.After(10 * time.Second):
2044 t.Fatal("no load started")
2045 }
2046 goroutines := runtime.NumGoroutine()
2047 files, listed := openFiles(t)
2048
2049 flood := 4 * MaxLoadWaiting
2050 served := get(flood)
2051 refused := flood - (MaxLoadWaiting - 1)
2052 for range refused {
2053 if w := <-served; w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
2054 t.Fatalf("a request past MaxLoadWaiting answered %d", w.Code)
2055 }
2056 }
2057 if n := len(h.srv.loadWaiting); n != MaxLoadWaiting {
2058 t.Errorf("%d requests wait for the load, not %d", n, MaxLoadWaiting)
2059 }
2060 const slack = 8
2061 eventually(t, "the refused requests' goroutines end", func() bool {
2062 return runtime.NumGoroutine() <= goroutines+MaxLoadWaiting-1+slack
2063 })
2064 if n, _ := openFiles(t); listed && n > files+slack {
2065 t.Errorf("the flood holds %d files open, %d more than before it", n, n-files)
2066 }
2067
2068 close(hold)
2069 for range MaxLoadWaiting - 1 {
2070 if w := <-served; w.Code != http.StatusOK {
2071 t.Errorf("a request that waited for the load answered %d", w.Code)
2072 }
2073 }
2074 if w := <-first; w.Code != http.StatusOK {
2075 t.Errorf("the request that started the load answered %d", w.Code)
2076 }
2077 if n := reads.Load(); n != 1 {
2078 t.Errorf("the export was read %d times for one generation", n)
2079 }
2080 if n := len(h.srv.loadWaiting); n != 0 {
2081 t.Errorf("%d requests still hold a place among those that wait", n)
2082 }
2083}
2084
2085// A request's time runs from its arrival through its rendering: a request
2086// for a page that runs no git, held past its time before it renders,
2087// answers 503, and the server logs it.
2088func TestRenderingIsWithinTheDeadline(t *testing.T) {
2089 h := newHarness(t)
2090 h.page("/")
2091 h.srv.timeout = 50 * time.Millisecond
2092 var logged []string
2093 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
2094 h.srv.opened = func(export.Generation) { time.Sleep(100 * time.Millisecond) }
2095 if w := h.get("/"); w.Code != http.StatusServiceUnavailable || !bytes.Equal(w.Body.Bytes(), busyPage) {
2096 t.Errorf("a request that ran out of time before it rendered answered %d", w.Code)
2097 }
2098 if len(logged) != 1 || !strings.Contains(logged[0], "rendering plan: context deadline exceeded") {
2099 t.Errorf("the server logged %q", logged)
2100 }
2101 if n, _ := h.srv.holding(); n != 0 {
2102 t.Errorf("a page that stopped rendering kept %d pieces of the budget", n)
2103 }
2104}
2105
2106// A FIFO with a writer that sends no bytes keeps Read blocked until the
2107// request deadline. A FIFO without a writer must not block Open.
2108func TestStalledLoadReleasesGeneration(t *testing.T) {
2109 for _, writer := range []bool{false, true} {
2110 t.Run(fmt.Sprint(writer), func(t *testing.T) {
2111 h := newHarness(t)
2112 h.srv.timeout = 100 * time.Millisecond
2113 h.srv.log = func(error) {}
2114 old := h.active()
2115 data, err := os.ReadFile(old.ExportPath())
2116 if err != nil {
2117 t.Fatal(err)
2118 }
2119 if err := os.Remove(old.ExportPath()); err != nil {
2120 t.Fatal(err)
2121 }
2122 if err := syscall.Mkfifo(old.ExportPath(), 0600); err != nil {
2123 t.Fatal(err)
2124 }
2125 if writer {
2126 f, err := os.OpenFile(old.ExportPath(), os.O_RDWR|syscall.O_NONBLOCK, 0)
2127 if err != nil {
2128 t.Fatal(err)
2129 }
2130 defer f.Close()
2131 if _, err := f.Write([]byte("{")); err != nil {
2132 t.Fatal(err)
2133 }
2134 }
2135 if w := h.get("/"); w.Code != http.StatusServiceUnavailable {
2136 t.Fatalf("status = %d", w.Code)
2137 }
2138 eventually(t, "the stalled worker exits", func() bool { return len(h.srv.loaders) == 0 })
2139 h.srv.mu.Lock()
2140 cached := h.srv.cached
2141 h.srv.mu.Unlock()
2142 if cached != nil {
2143 t.Fatal("stalled load cached a snapshot")
2144 }
2145 if err := os.Remove(old.ExportPath()); err != nil {
2146 t.Fatal(err)
2147 }
2148 if err := os.WriteFile(old.ExportPath(), data, 0644); err != nil {
2149 t.Fatal(err)
2150 }
2151 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan"))
2152 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
2153 t.Fatalf("generation retained: %v", err)
2154 }
2155 h.srv.timeout = requestTimeout
2156 if !strings.Contains(h.page("/app/knots/oc-a000001"), "The second plan") {
2157 t.Fatal("loader slot is not reusable")
2158 }
2159 })
2160 }
2161}
2162
2163// cancelInPhase cancels a real context on the third cancellation check
2164// inside a named processing function. It makes cancellation during CPU
2165// work deterministic without replacing decoding or graph traversal.
2166type cancelInPhase struct {
2167 context.Context
2168 cancel context.CancelFunc
2169 phase string
2170 checks int
2171}
2172
2173func (c *cancelInPhase) Err() error {
2174 var pcs [32]uintptr
2175 n := runtime.Callers(2, pcs[:])
2176 frames := runtime.CallersFrames(pcs[:n])
2177 for {
2178 frame, more := frames.Next()
2179 if strings.HasSuffix(frame.Function, c.phase) {
2180 c.checks++
2181 if c.checks == 3 {
2182 c.cancel()
2183 }
2184 break
2185 }
2186 if !more {
2187 break
2188 }
2189 }
2190 return c.Context.Err()
2191}
2192
2193func TestProcessingCancellationReleasesGeneration(t *testing.T) {
2194 for _, phase := range []string{".decodeValue", ".(*Export).ValidateContext", ".(*index).planPage", ".(*index).paths", ".(*index).milestones"} {
2195 t.Run(phase, func(t *testing.T) {
2196 h := newHarness(t)
2197 old := h.active()
2198 base, cancel := context.WithCancel(context.Background())
2199 defer cancel()
2200 ctx := &cancelInPhase{Context: base, cancel: cancel, phase: phase}
2201 l := &load{done: make(chan struct{}), cancel: cancel}
2202 h.srv.loads[l] = struct{}{}
2203 h.srv.loaders <- struct{}{}
2204 finished := make(chan struct{})
2205 go func() { h.srv.run(ctx, l); close(finished) }()
2206 select {
2207 case <-finished:
2208 case <-time.After(2 * time.Second):
2209 t.Fatal("processing did not stop")
2210 }
2211 if ctx.checks < 3 {
2212 t.Fatalf("phase was not reached: %d checks", ctx.checks)
2213 }
2214 if !errors.Is(l.err, context.Canceled) {
2215 t.Fatalf("load error = %v", l.err)
2216 }
2217 if h.srv.cached != nil || len(h.srv.loaders) != 0 || len(h.srv.loads) != 0 {
2218 t.Fatal("cancelled processing retained load state")
2219 }
2220 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan"))
2221 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
2222 t.Fatalf("generation retained: %v", err)
2223 }
2224 if !strings.Contains(h.page("/app/knots/oc-a000001"), "The second plan") {
2225 t.Fatal("loader slot is not reusable")
2226 }
2227 })
2228 }
2229}