gunk-dev/the-valley

server_test.go

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