gunk-dev/the-valley

server_test.go

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