gunk-dev/the-valley

server_test.go

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