gunk-dev/the-valley

server_test.go

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