gunk-dev/the-valley

server_test.go

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