gunk-dev/the-valley

reader_test.go

source1391837a95fbmain's published tip history
62.5 KiB
1package server
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "maps"
9 "net/http"
10 "net/http/httptest"
11 "path/filepath"
12 "reflect"
13 "slices"
14 "sort"
15 "strings"
16 "sync"
17 "sync/atomic"
18 "testing"
19 "time"
20
21 "the-valley/web/export"
22 "the-valley/web/export/exporttest"
23)
24
25// readerKey is the request context's key under which a test names the
26// reader a request is read as.
27type readerKey struct{}
28
29// as answers a request for target read as reader, with header's fields.
30func (h *harness) as(reader, method, target string, header http.Header) *httptest.ResponseRecorder {
31 h.t.Helper()
32 r := httptest.NewRequest(method, target, nil)
33 for k, vs := range header {
34 r.Header[k] = vs
35 }
36 r = r.WithContext(context.WithValue(r.Context(), readerKey{}, reader))
37 w := httptest.NewRecorder()
38 h.srv.ServeHTTP(w, r)
39 return w
40}
41
42// pageAs is the body of a GET read as reader that must answer 200.
43func (h *harness) pageAs(reader, target string) string {
44 h.t.Helper()
45 w := h.as(reader, "GET", target, nil)
46 if w.Code != http.StatusOK {
47 h.t.Fatalf("GET %s as %s answered %d:\n%s", target, reader, w.Code, w.Body)
48 }
49 return w.Body.String()
50}
51
52// The publication identities these tests give site, which the fixture
53// does not export, and docs, which the tests make of site.
54const (
55 siteIdentity = "273d5668702918ea7ae079de374db96b"
56 docsIdentity = "5b1e0c7a9f3d2e4c6a8b0d1f3e5c7a92"
57)
58
59// buildExport is the fixture's valley exported by export.Build, as a
60// publisher builds it, with its plan changed by change first, when change
61// is not nil: change is given the plan's knot of a project by ID. With
62// site set, site is exported too, as for an edge where site has a named
63// reader, and bundles holds its bundle.
64func (h *harness) buildExport(site bool, change func(knot func(project, id string) map[string]any)) (e *export.Export, bundles map[string]string) {
65 t := h.t
66 t.Helper()
67 var plan map[string]any
68 if err := json.Unmarshal(h.f.Inputs.Plan, &plan); err != nil {
69 t.Fatal(err)
70 }
71 project := func(name string) map[string]any {
72 for _, p := range plan["projects"].([]any) {
73 if p := p.(map[string]any); p["project"] == name {
74 return p
75 }
76 }
77 t.Fatalf("the fixture's plan has no project %s", name)
78 return nil
79 }
80 knot := func(name, id string) map[string]any {
81 for _, k := range project(name)["knots"].([]any) {
82 if k := k.(map[string]any); k["id"] == id {
83 return k
84 }
85 }
86 t.Fatalf("the fixture's plan has no knot %s:%s", name, id)
87 return nil
88 }
89 if change != nil {
90 change(knot)
91 }
92 data, err := json.Marshal(plan)
93 if err != nil {
94 t.Fatal(err)
95 }
96 in := h.f.Inputs
97 in.Plan = data
98 in.Identities = map[string]string{"app": exporttest.Identities["app"]}
99 in.SourceTips = map[string]string{"app": h.f.Inputs.SourceTips["app"]}
100 in.Details = slices.Clone(h.f.Inputs.Details)
101 bundles = map[string]string{}
102 if site {
103 in.Identities["site"] = siteIdentity
104 in.SourceTips["site"] = git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef)
105 for _, k := range project("site")["knots"].([]any) {
106 id := k.(map[string]any)["id"].(string)
107 detail, err := json.Marshal(map[string]any{"schema": "valley-knot/v1", "project": "site", "tip": project("site")["tip"],
108 "knot": map[string]any{"id": id, "body": "What site says of " + id + ".\n", "comments": []any{}}})
109 if err != nil {
110 t.Fatal(err)
111 }
112 in.Details = append(in.Details, detail)
113 }
114 bundles["site"] = filepath.Join(t.TempDir(), "site.bundle")
115 git(t, h.f.Repos["site"], nil, "bundle", "create", "--quiet", bundles["site"], "main")
116 }
117 if e, err = export.Build(in); err != nil {
118 t.Fatal(err)
119 }
120 return e, bundles
121}
122
123// withDocs adds to e a project docs, a copy of site with an identity of
124// its own, in a group of its own, pages, whose alias is p. docs was
125// renamed from old-docs, and has the short alias d. Its bundle is site's.
126func withDocs(e *export.Export, bundles map[string]string) {
127 var site export.Project
128 for _, p := range e.Projects {
129 if p.Name == "site" {
130 site = p
131 }
132 }
133 docs := site
134 docs.Name, docs.Identity, docs.Group, docs.WebName = "docs", docsIdentity, "web", "docs"
135 docs.FormerNames, docs.Aliases = []string{"old-docs"}, []string{"d"}
136 e.Projects = append(e.Projects, docs)
137 sort.Slice(e.Projects, func(i, j int) bool { return e.Projects[i].Name < e.Projects[j].Name })
138 e.Groups = append(e.Groups, export.Group{ID: "web", Name: "pages", Aliases: []string{"p"}})
139 bundles["docs"] = bundles["site"]
140}
141
142// authorizeReaders stores an authorization one sequence past the stored
143// one's that lets the readers given for each project of e read it, under
144// e's identity. A project given no reader is not named. The policy check's
145// time is kept, so the pages' freshness does not change.
146func (h *harness) authorizeReaders(e *export.Export, readers map[string][]string) {
147 h.t.Helper()
148 a, _, err := h.store.Authorization()
149 if err != nil {
150 h.t.Fatal(err)
151 }
152 next := &export.Authorization{Instance: exporttest.Instance, Destination: exporttest.Destination,
153 Sequence: a.Sequence + 1, Checked: a.Checked}
154 for _, p := range e.Projects {
155 if rs := readers[p.Name]; len(rs) > 0 {
156 next.Projects = append(next.Projects, export.AuthorizedProject{Name: p.Name, Identity: p.Identity, Readers: rs})
157 }
158 }
159 h.authorize(next)
160}
161
162// edge activates, signed at, an export that holds app, site and docs, as
163// an edge holds them for site's and docs' named readers, and stores an
164// authorization that lets the readers given for each read it. It returns
165// the export.
166func (h *harness) edge(at time.Time, readers map[string][]string) *export.Export {
167 h.t.Helper()
168 e, bundles := h.buildExport(true, nil)
169 withDocs(e, bundles)
170 h.authorizeReaders(e, readers)
171 h.publishExport(at, e, bundles)
172 return e
173}
174
175// anonymousIndex is the index of the newest generation's view of what
176// anyone may see, under the last authorization read.
177func (s *Server) anonymousIndex() *index {
178 s.mu.Lock()
179 defer s.mu.Unlock()
180 var newest *view
181 for _, v := range s.views {
182 if v.idx != nil && maps.Equal(v.shown, visible(v.e, s.auth.a, export.Anyone)) && (newest == nil || v.key.seq > newest.key.seq) {
183 newest = v
184 }
185 }
186 if newest == nil {
187 return nil
188 }
189 return newest.idx
190}
191
192// heldSlots is how many source requests hold a git slot, and
193// waitingForSlots how many wait for one.
194func (s *Server) heldSlots() int {
195 s.gitMu.Lock()
196 defer s.gitMu.Unlock()
197 return s.running
198}
199
200func (s *Server) waitingForSlots() int {
201 s.gitMu.Lock()
202 defer s.gitMu.Unlock()
203 return len(s.queue)
204}
205
206// runningLoads is how many loader slots loads hold.
207func (s *Server) runningLoads() int { return len(s.anonLoader) + len(s.loaders) }
208
209// loadWaiters counts the requests that wait for the loads a request may
210// still join, anonymous and named apart.
211func (s *Server) loadWaiters() (anonymous, named int) {
212 s.mu.Lock()
213 defer s.mu.Unlock()
214 for l := range s.loads {
215 anonymous += l.anon
216 named += l.wants - l.anon
217 }
218 return anonymous, named
219}
220
221// stoppingViews counts the views whose builds were stopped and whose
222// workers have not ended.
223func (s *Server) stoppingViews() int {
224 s.mu.Lock()
225 defer s.mu.Unlock()
226 return len(s.stopping)
227}
228
229// heldViews counts the places of each pool that the views the server
230// holds take, and the pins on all of them. A stopped build's place is not
231// counted.
232func (s *Server) heldViews() (anonymous, named, pins int) {
233 s.mu.Lock()
234 defer s.mu.Unlock()
235 for _, v := range s.views {
236 if v.holds[anonymousPool] {
237 anonymous++
238 }
239 if v.holds[namedPool] {
240 named++
241 }
242 pins += v.pins[anonymousPool] + v.pins[namedPool]
243 }
244 return anonymous, named, pins
245}
246
247// Each reader is served from the projects they may see: what anyone may
248// read, app, and what their principal may read, site for alice and docs
249// for bob. For each reader, every route, the navigation, the landing, the
250// aliases, the former names, the references between projects, the
251// rendered Markdown and the archives are built from those projects alone.
252// A project the reader may not see answers every route exactly as one that
253// does not exist, takes no git slot, and its group's alias, when none of
254// the group's projects is the reader's, is no alias.
255func TestNamedReadersSeeTheirOwnProjects(t *testing.T) {
256 h := newHarness(t)
257 h.edge(exporttest.SignedAt.Add(time.Minute), map[string][]string{
258 "app": {export.Anyone}, "site": {"alice"}, "docs": {"bob"}})
259 appTip, siteTip := h.tip(), git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef)
260 var admitted atomic.Int32
261 h.srv.admitted = func() { admitted.Add(1) }
262
263 type project struct{ base, tip, readme string }
264 projects := map[string]project{
265 "app": {"/tools/app", appTip, `<h1 id="app">`},
266 "site": {"/tools/site", siteTip, `<h1 id="site">`},
267 "docs": {"/pages/docs", siteTip, `<h1 id="site">`},
268 }
269 readers := map[string][]string{export.Anyone: {"app"}, "alice": {"app", "site"}, "bob": {"app", "docs"}}
270 for reader, sees := range readers {
271 t.Run(reader, func(t *testing.T) {
272 // The navigation, the knots page and the landing.
273 plan := h.pageAs(reader, "/-/knots")
274 nav := section(t, plan, `<nav class="site"`, `<span class="fresh">`)
275 var want strings.Builder
276 want.WriteString(`<nav class="site" aria-label="Pages"><a href="/-/knots">knots</a>`)
277 for _, name := range sees {
278 fmt.Fprintf(&want, `<a href="%s/source/tree/%s/">%s source</a>`, projects[name].base, projects[name].tip, name)
279 }
280 if nav != want.String() {
281 t.Errorf("the navigation is\n%s\nnot\n%s", nav, want.String())
282 }
283 if !strings.Contains(plan, "Policy last checked") {
284 t.Error("the knots page does not say when the policy was checked")
285 }
286 if w := h.as(reader, "GET", "/", nil); w.Code != http.StatusFound || w.Header().Get("Location") != "/tools/app/source/tree/"+appTip+"/" {
287 t.Errorf("/ answered %d to %q", w.Code, w.Header().Get("Location"))
288 }
289 seesSite := slices.Contains(sees, "site")
290 if strings.Contains(plan, "/tools/site/knots/") != seesSite {
291 t.Errorf("the knots page shows site's knots %v, though the reader sees site %v", !seesSite, seesSite)
292 }
293 if strings.Contains(plan, "/pages/docs/") != slices.Contains(sees, "docs") {
294 t.Error("the knots page links docs's knots to a reader who may not see it, or not to one who may")
295 }
296
297 // The references from app's knots into site.
298 blocked := h.pageAs(reader, "/tools/app/knots/oc-a000003") + h.pageAs(reader, "/tools/app/knots/bd-a000004")
299 for text, shown := range map[string]bool{
300 `<a href="/tools/site/knots/oc-b000001">The site deploys the app</a>`: seesSite,
301 `<dt>Lands in</dt><dd><a href="/tools/site/source/tree/` + siteTip + `/">site</a></dd>`: seesSite,
302 `<dt>Lands in</dt><dd><a href="/tools/site/knots/oc-b000002">site:oc-b000002</a></dd>`: seesSite,
303 `<span class="t"><span class="muted">a knot in an unpublished project</span></span>`: !seesSite,
304 "<dt>Lands in</dt><dd>an unpublished project</dd>": !seesSite,
305 "<dt>Lands in</dt><dd>a knot in an unpublished project</dd>": !seesSite,
306 "site:oc-b000001": seesSite,
307 "The site serves the docs": false,
308 } {
309 if strings.Contains(blocked, text) != shown {
310 t.Errorf("app's blocked knots show %q %v, not %v", text, !shown, shown)
311 }
312 }
313
314 // Each project the reader may see, on every route.
315 for _, name := range sees {
316 p := projects[name]
317 admitted.Store(0)
318 if page := h.pageAs(reader, p.base+"/source/tree/"+p.tip+"/"); !strings.Contains(page, p.readme) {
319 t.Errorf("%s's tree does not render its README", name)
320 }
321 h.pageAs(reader, p.base+"/source/blob/"+p.tip+"/README.md")
322 h.pageAs(reader, p.base+"/source/log/"+p.tip)
323 archive := h.as(reader, "GET", p.base+"/source/archive/"+p.tip+".tar.gz", nil)
324 if archive.Code != http.StatusOK || !strings.Contains(archive.Header().Get("Content-Disposition"), name+"-"+p.tip[:12]+".tar.gz") {
325 t.Errorf("%s's archive answered %d, %q", name, archive.Code, archive.Header().Get("Content-Disposition"))
326 } else if _, ok := archiveEntries(t, archive.Body.Bytes())[name+"-"+p.tip[:12]+"/README.md"]; !ok {
327 t.Errorf("%s's archive does not hold its README", name)
328 }
329 if n := admitted.Load(); n != 4 {
330 t.Errorf("%s's four source routes took %d git slots", name, n)
331 }
332 for target, to := range map[string]string{
333 p.base + "/": p.base + "/source/tree/" + p.tip + "/",
334 p.base + "/source/": p.base + "/source/tree/" + p.tip + "/",
335 p.base + "/source/archive/main.tar.gz": p.base + "/source/archive/" + p.tip + ".tar.gz",
336 } {
337 if w := h.as(reader, "GET", target, nil); w.Code != http.StatusFound || w.Header().Get("Location") != to {
338 t.Errorf("GET %s answered %d to %q, not to %s", target, w.Code, w.Header().Get("Location"), to)
339 }
340 }
341 }
342 aliases := map[string]string{
343 "/t/app/": "/tools/app/", "/tools/old-app/": "/tools/app/", "/app/knots/oc-a000002": "/tools/app/knots/oc-a000002",
344 "/t/site/": "/tools/site/", "/t/nosuch/": "/tools/nosuch/",
345 }
346 if seesSite {
347 aliases["/site/"], aliases["/tools/old-site/"] = "/tools/site/", "/tools/site/"
348 }
349 if slices.Contains(sees, "docs") {
350 aliases["/p/docs/"], aliases["/d/"], aliases["/pages/old-docs/x"] = "/pages/docs/", "/pages/docs/", "/pages/docs/x"
351 }
352 for from, to := range aliases {
353 if w := h.as(reader, "GET", from, nil); w.Code != http.StatusPermanentRedirect || w.Header().Get("Location") != to {
354 t.Errorf("GET %s answered %d to %q, not to %s", from, w.Code, w.Header().Get("Location"), to)
355 }
356 }
357
358 // Each project the reader may not see answers as one that does
359 // not exist, on every route, and takes no git slot.
360 missing := h.as(reader, "GET", "/tools/nosuch/", nil)
361 for _, name := range []string{"site", "docs"} {
362 if slices.Contains(sees, name) {
363 continue
364 }
365 p := projects[name]
366 admitted.Store(0)
367 var hidden []string
368 for _, route := range []string{"", "/", "/knots/oc-b000001", "/source", "/source/", "/source/tree/" + p.tip + "/",
369 "/source/blob/" + p.tip + "/README.md", "/source/log/" + p.tip, "/source/archive/" + p.tip + ".tar.gz",
370 "/source/archive/main.tar.gz"} {
371 hidden = append(hidden, p.base+route)
372 }
373 if name == "site" {
374 hidden = append(hidden, "/site/", "/site/knots/oc-b000001", "/tools/old-site/source/")
375 } else {
376 hidden = append(hidden, "/p/docs/", "/p/", "/d/", "/pages/old-docs/", "/pages/")
377 }
378 for _, target := range hidden {
379 w := h.as(reader, "GET", target, nil)
380 if w.Code != http.StatusNotFound || fmt.Sprint(w.Header()) != fmt.Sprint(missing.Header()) ||
381 !bytes.Equal(w.Body.Bytes(), missing.Body.Bytes()) {
382 t.Errorf("GET %s answered %d, not as a project that does not exist", target, w.Code)
383 }
384 }
385 if n := admitted.Load(); n != 0 {
386 t.Errorf("the routes of %s, which the reader may not see, took %d git slots", name, n)
387 }
388 }
389 })
390 }
391
392 // With app withdrawn from anyone, / lands on the first project each
393 // reader may see, and on the knots page for a reader who may see none.
394 e, _ := h.buildExport(true, nil)
395 withDocs(e, map[string]string{"site": ""})
396 h.authorizeReaders(e, map[string][]string{"app": {"carol"}, "site": {"alice"}, "docs": {"bob"}})
397 for reader, to := range map[string]string{export.Anyone: knotsURL, "alice": "/tools/site/source/tree/" + siteTip + "/",
398 "bob": "/pages/docs/source/tree/" + siteTip + "/", "carol": "/tools/app/source/tree/" + appTip + "/"} {
399 if w := h.as(reader, "GET", "/", nil); w.Code != http.StatusFound || w.Header().Get("Location") != to {
400 t.Errorf("/ as %s answered %d to %q, not to %s", reader, w.Code, w.Header().Get("Location"), to)
401 }
402 }
403 if w := h.as(export.Anyone, "GET", "/t/app/", nil); w.Code != http.StatusNotFound {
404 t.Errorf("a group none of whose projects anyone may see kept its alias: %d", w.Code)
405 }
406}
407
408// A reader may see a project when the authorization names it, under the
409// identity the export gives it, for anyone or for the reader's principal:
410// the union of the two. A grant under another identity grants nothing.
411func TestVisibilityIsTheUnionUnderThePublicationIdentity(t *testing.T) {
412 e := &export.Export{Groups: []export.Group{{ID: "core", Name: "tools"}}, Projects: []export.Project{
413 {Name: "app", Identity: exporttest.Identities["app"], Group: "core"},
414 {Name: "loose", Identity: docsIdentity},
415 {Name: "site", Identity: siteIdentity, Group: "core"},
416 }}
417 a := &export.Authorization{Projects: []export.AuthorizedProject{
418 {Name: "app", Identity: exporttest.Identities["app"], Readers: []string{"alice"}},
419 {Name: "loose", Identity: docsIdentity, Readers: []string{export.Anyone, "alice"}},
420 {Name: "site", Identity: siteIdentity, Readers: []string{export.Anyone, "bob"}},
421 }}
422 for reader, want := range map[string][]string{
423 export.Anyone: {"site"}, "alice": {"app", "site"}, "bob": {"site"}, "carol": {"site"},
424 } {
425 var got []string
426 for name := range visible(e, a, reader) {
427 got = append(got, name)
428 }
429 sort.Strings(got)
430 if !slices.Equal(got, want) {
431 t.Errorf("%s may see %v, not %v", reader, got, want)
432 }
433 }
434 a.Projects[0].Identity = siteIdentity
435 if shown := visible(e, a, "alice"); shown["app"] {
436 t.Error("a grant under another identity lets alice see app")
437 }
438 if shown := visible(e, nil, "alice"); len(shown) != 0 {
439 t.Errorf("no authorization lets alice see %v", shown)
440 }
441}
442
443// Readers who may see the same projects share one index, and a named
444// reader who may see no more than anyone shares anyone's. The index names
445// no reader, and neither does any page built from it.
446func TestIdenticalViewsShareAnIndex(t *testing.T) {
447 h := newHarness(t)
448 h.edge(exporttest.SignedAt.Add(time.Minute), map[string][]string{
449 "app": {export.Anyone}, "site": {"alice", "carol"}, "docs": {"bob"}})
450 var built []string
451 var mu sync.Mutex
452 h.srv.indexing = func(_ context.Context, key viewKey) {
453 mu.Lock()
454 defer mu.Unlock()
455 built = append(built, key.projects)
456 }
457 pages := map[string]string{}
458 for _, reader := range []string{export.Anyone, "alice", "carol", "dave", "alice", export.Anyone} {
459 pages[reader] = h.pageAs(reader, "/-/knots") + h.pageAs(reader, "/tools/app/knots/oc-a000003")
460 }
461 if len(built) != 2 {
462 t.Errorf("the server built %d indexes for two views:\n%s", len(built), strings.Join(built, "--\n"))
463 }
464 if anonymous, named, pins := h.srv.heldViews(); anonymous != 1 || named != 1 || pins != 0 {
465 t.Errorf("the server holds %d views of what anyone may see and %d others, pinned %d times", anonymous, named, pins)
466 }
467 if pages["alice"] != pages["carol"] || pages["dave"] != pages[export.Anyone] || pages["alice"] == pages[export.Anyone] {
468 t.Error("readers who may see the same projects were served other pages")
469 }
470 for reader, page := range pages {
471 for _, name := range []string{"alice", "carol", "dave", "bob"} {
472 if strings.Contains(page, name) {
473 t.Errorf("the page served to %s names %s", reader, name)
474 }
475 }
476 }
477}
478
479// A knot whose one blocker is in a project the reader may not see reads
480// the same whether the export leaves that project out or holds it for
481// another reader: its projected fields, the knots page and its own page
482// are the same, byte for byte. Its blocker done, neither says it waits;
483// its blocker open, both say once that it waits on something the reader
484// may not see.
485func TestAHiddenBlockerReadsAlikeInEitherExport(t *testing.T) {
486 for _, status := range []string{"done", "open"} {
487 t.Run(status, func(t *testing.T) {
488 h := newHarness(t)
489 change := func(knot func(project, id string) map[string]any) {
490 k := knot("app", "oc-a000003")
491 k["blocked_by"] = []any{"site:oc-b000001"}
492 k["waiting_on"], k["state"], k["ready"] = []any{"site:oc-b000001"}, "blocked", false
493 k["edges"].([]any)[0].(map[string]any)["status"] = status
494 knot("app", "oc-a000002")["blocks"] = []any{}
495 if status == "done" {
496 k["waiting_on"], k["state"], k["ready"] = []any{}, "ready", true
497 b := knot("site", "oc-b000001")
498 b["status"], b["active"], b["state"], b["ready"] = "done", false, "done", false
499 }
500 }
501 targets := []string{"/-/knots", "/tools/app/knots/oc-a000003", "/tools/app/knots/bd-a000004", "/tools/app/knots/oc-a000001"}
502 served := func(at time.Time, site bool) (map[string]string, *export.Project) {
503 t.Helper()
504 e, bundles := h.buildExport(site, change)
505 h.authorizeReaders(e, map[string][]string{"app": {export.Anyone}, "site": {"alice"}})
506 h.publishExport(at, e, bundles)
507 pages := map[string]string{}
508 for _, target := range targets {
509 pages[target] = h.page(target)
510 }
511 return pages, h.srv.anonymousIndex().projects["app"]
512 }
513 without, projectedWithout := served(exporttest.SignedAt.Add(time.Minute), false)
514 with, projectedWith := served(exporttest.SignedAt.Add(2*time.Minute), true)
515 if !reflect.DeepEqual(projectedWithout, projectedWith) {
516 t.Errorf("app is projected one way from the export without site and another from the one with it:\n%+v\n%+v",
517 projectedWithout.Knots[2], projectedWith.Knots[2])
518 }
519 for _, target := range targets {
520 if without[target] != with[target] {
521 t.Errorf("GET %s answered one page from the export without site and another from the one with it", target)
522 }
523 }
524 plan := with["/-/knots"]
525 switch status {
526 case "done":
527 if strings.Contains(plan, `class="chip blocked"`) {
528 t.Error("a knot whose hidden blocker is done is shown waiting")
529 }
530 case "open":
531 if strings.Count(plan, `<span class="chip blocked">`) != 1 ||
532 !strings.Contains(plan, `<span class="chip blocked">waits on a knot in an unpublished project</span>`) {
533 t.Errorf("a knot whose hidden blocker is open does not say once that it waits:\n%s", section(t, plan, `id="ms-h"`, "</body>"))
534 }
535 }
536 for _, page := range with {
537 for _, unwanted := range append([]string{"/tools/site/"}, unpublishedText...) {
538 if strings.Contains(page, unwanted) {
539 t.Errorf("a page holds %q", unwanted)
540 }
541 }
542 }
543 if page := h.pageAs("alice", "/tools/app/knots/oc-a000003"); !strings.Contains(page, `<a href="/tools/site/knots/oc-b000001">The site deploys the app</a>`) {
544 t.Error("alice, who may see site, is not shown the blocker")
545 }
546 })
547 }
548}
549
550// The projection copies the projects a reader may see, and of each knot
551// keeps what it says of those projects and the export's opaque summary
552// alone: the references into other projects leave its four derived lists,
553// its WaitingOnHidden is set when one leaves WaitingOn, and its edges into
554// them are hidden, with nothing of their targets kept. The export it reads
555// does not change.
556func TestProjectionHidesOtherProjects(t *testing.T) {
557 h := newHarness(t)
558 e, _ := h.buildExport(true, nil)
559 app := &e.Projects[0]
560 at := slices.IndexFunc(app.Knots, func(k export.Knot) bool { return k.ID == "oc-a000003" })
561 k := &app.Knots[at]
562 why, status, title := "a reason", "open", "A title of site's"
563 // "site" alone is neither a knot's ID nor <project>:<id>, so it names
564 // no knot the reader may see, and is taken out.
565 k.WaitingOn = []string{"oc-a000002", "site:oc-b000001", "app:oc-a000006", "gone:oc-c000001", "site"}
566 k.ClearedByEnding = []string{"site:oc-b000002", "oc-a000006"}
567 k.Dangling = []string{"site:oc-bfffff1", "app:oc-afffff1"}
568 k.Unresolved = []string{"site:oc-b000003", "oc-a000001", "site"}
569 k.Edges = []export.Edge{
570 {Field: "blocked_by", Ref: "site:oc-b000001", Project: "site", ID: "oc-b000001", State: export.EdgeResolved, Why: &why, Status: &status, Title: &title},
571 {Field: "blocked_by", Ref: "site:oc-bfffff1", Project: "site", ID: "oc-bfffff1", State: export.EdgeDangling, Why: &why},
572 {Field: "blocked_by", Ref: "app:oc-afffff1", Project: "app", ID: "oc-afffff1", State: export.EdgeDangling},
573 {Field: "target", Ref: "gone:oc-c000001", Project: "gone", ID: "oc-c000001", State: export.EdgeHidden},
574 }
575 before, err := e.Encode()
576 if err != nil {
577 t.Fatal(err)
578 }
579 projected, err := projectForReader(context.Background(), e, map[string]bool{"app": true})
580 if err != nil {
581 t.Fatal(err)
582 }
583 if len(projected.Projects) != 1 || projected.Projects[0].Name != "app" || len(projected.Groups) != 1 {
584 t.Fatalf("the projection holds %d projects and %d groups", len(projected.Projects), len(projected.Groups))
585 }
586 got := projected.Projects[0].Knots[at]
587 hide := func(edge export.Edge) export.Edge {
588 return export.Edge{Field: edge.Field, Ref: edge.Ref, Project: edge.Project, ID: edge.ID, State: export.EdgeHidden}
589 }
590 for field, c := range map[string][2]any{
591 "WaitingOn": {got.WaitingOn, []string{"oc-a000002", "app:oc-a000006"}},
592 "WaitingOnHidden": {got.WaitingOnHidden, true},
593 "ClearedByEnding": {got.ClearedByEnding, []string{"oc-a000006"}},
594 "Dangling": {got.Dangling, []string{"app:oc-afffff1"}},
595 "Unresolved": {got.Unresolved, []string{"oc-a000001"}},
596 "Edges": {got.Edges, []export.Edge{hide(k.Edges[0]), hide(k.Edges[1]), k.Edges[2], k.Edges[3]}},
597 "State": {got.State, k.State},
598 "Ready": {got.Ready, k.Ready},
599 "BlockedBy": {got.BlockedBy, k.BlockedBy},
600 } {
601 if !reflect.DeepEqual(c[0], c[1]) {
602 t.Errorf("the projected %s is %v, not %v", field, c[0], c[1])
603 }
604 }
605
606 // Everything kept for a reader who may see site, and the export read
607 // is the same bytes, though the copies change.
608 all, err := projectForReader(context.Background(), e, map[string]bool{"app": true, "site": true})
609 if err != nil {
610 t.Fatal(err)
611 }
612 if kept := all.Projects[0].Knots[at]; !reflect.DeepEqual(kept.WaitingOn, k.WaitingOn[:3]) || !kept.WaitingOnHidden ||
613 !reflect.DeepEqual(kept.Edges, k.Edges) || !reflect.DeepEqual(kept.Dangling, k.Dangling) || len(all.Projects) != 2 {
614 t.Errorf("a reader who may see site is not told what the export says of it: %+v", kept)
615 }
616 projected.Projects[0].Knots[at].Title = "changed"
617 projected.Projects[0].Knots[at].WaitingOn[0] = "changed"
618 projected.Projects[0].Knots[at].Edges[2].ID = "changed"
619 all.Projects[0].Knots[at].Dangling[0] = "changed"
620 if after, err := e.Encode(); err != nil || !bytes.Equal(before, after) {
621 t.Errorf("projecting the export, or changing a projection, changed the export: %v", err)
622 }
623}
624
625// privateViews activates an export that holds app, which anyone may
626// read, and four private projects, p1 to p4, copies of site. It stores an
627// authorization that lets each of the principals r1 to r15 read another
628// set of the four, so each of them has a view of their own. It returns the
629// export and its bundles.
630func (h *harness) privateViews() (*export.Export, map[string]string) {
631 h.t.Helper()
632 e, bundles := h.buildExport(true, nil)
633 var site export.Project
634 for _, p := range e.Projects {
635 if p.Name == "site" {
636 site = p
637 }
638 }
639 readers := map[string][]string{"app": {export.Anyone}}
640 for i := 1; i <= 4; i++ {
641 p := site
642 p.Name, p.WebName, p.Identity, p.FormerNames, p.Aliases = fmt.Sprintf("p%d", i), fmt.Sprintf("p%d", i), fmt.Sprintf("%032x", i), nil, nil
643 e.Projects = append(e.Projects, p)
644 bundles[p.Name] = bundles["site"]
645 for set := 1; set < 16; set++ {
646 if set&(1<<(i-1)) != 0 {
647 readers[p.Name] = append(readers[p.Name], fmt.Sprintf("r%d", set))
648 }
649 }
650 }
651 sort.Slice(e.Projects, func(i, j int) bool { return e.Projects[i].Name < e.Projects[j].Name })
652 h.authorizeReaders(e, readers)
653 h.publishExport(exporttest.SignedAt.Add(time.Minute), e, bundles)
654 return e, bundles
655}
656
657// serving answers a GET of target read as reader, under ctx, in a
658// goroutine of its own, and sends its response on the channel it returns.
659func (h *harness) serving(reader, target string, ctx context.Context) chan *httptest.ResponseRecorder {
660 served := make(chan *httptest.ResponseRecorder, 1)
661 go func() {
662 w := httptest.NewRecorder()
663 r := httptest.NewRequest("GET", target, nil)
664 h.srv.ServeHTTP(w, r.WithContext(context.WithValue(ctx, readerKey{}, reader)))
665 served <- w
666 }()
667 return served
668}
669
670// A target names a project, or a knot of one, and never a knot of its
671// own graph, so a project may be named as a knot's ID and still be a
672// project. Here oc-c000001, a copy of site that alice alone may read, is
673// the target of app's oc-a000003. A reader who may not see it is told the
674// knot lands in an unpublished project, on its page and on the knots
675// page, and no page of theirs names it. alice is shown it and linked to
676// its source. The other references a knot's page names are held to their
677// own fields: graduated_into names a knot of the knot's own graph, and a
678// blocked_by entry, a waiting_on entry or a changes link that names a
679// hidden project in neither of the shapes its field allows names nothing
680// of it.
681func TestATargetNamesNoProjectTheReaderMayNotSee(t *testing.T) {
682 h := newHarness(t)
683 e, bundles := h.buildExport(true, nil)
684 const hidden = "oc-c000001"
685 for _, p := range e.Projects {
686 if p.Name == "site" {
687 p.Name, p.WebName, p.Identity, p.FormerNames, p.Aliases = hidden, hidden, fmt.Sprintf("%032x", 0xc1), nil, nil
688 e.Projects = append(e.Projects, p)
689 bundles[hidden] = bundles["site"]
690 break
691 }
692 }
693 sort.Slice(e.Projects, func(i, j int) bool { return e.Projects[i].Name < e.Projects[j].Name })
694 app := &e.Projects[0]
695 for i := range app.Knots {
696 switch k := &app.Knots[i]; k.ID {
697 case "oc-a000003":
698 k.Target = hidden
699 k.BlockedBy = append(k.BlockedBy, "site")
700 k.WaitingOn = append(k.WaitingOn, "site")
701 k.Changes = append(k.Changes, "valley:site")
702 case "bd-a000004":
703 k.GraduatedInto = "oc-a000002"
704 case "oc-a000006":
705 k.GraduatedInto = "site"
706 }
707 }
708 h.authorizeReaders(e, map[string][]string{"app": {export.Anyone}, hidden: {"alice"}})
709 h.publishExport(exporttest.SignedAt.Add(time.Minute), e, bundles)
710 tip := git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef)
711
712 for reader, sees := range map[string]bool{export.Anyone: false, "bob": false, "alice": true} {
713 t.Run(reader, func(t *testing.T) {
714 knot := h.pageAs(reader, "/tools/app/knots/oc-a000003")
715 plan := h.pageAs(reader, "/-/knots")
716 lands := "<dt>Lands in</dt><dd>an unpublished project</dd>"
717 chip := `<span class="chip quiet">lands in an unpublished project</span>`
718 if sees {
719 lands = `<dt>Lands in</dt><dd><a href="/tools/` + hidden + `/source/tree/` + tip + `/">` + hidden + `</a></dd>`
720 chip = `<span class="chip quiet">lands in ` + hidden + `</span>`
721 }
722 if !strings.Contains(knot, lands) {
723 t.Errorf("oc-a000003's page does not show %q", lands)
724 }
725 if !strings.Contains(plan, chip) {
726 t.Errorf("the knots page does not show %q", chip)
727 }
728
729 // Every page the reader may see of app, and the landing.
730 pages := []string{knot, plan}
731 for _, k := range app.Knots {
732 pages = append(pages, h.pageAs(reader, "/tools/app/knots/"+k.ID))
733 }
734 pages = append(pages, h.pageAs(reader, "/tools/app/source/tree/"+h.tip()+"/"))
735 if w := h.as(reader, "GET", "/", nil); w.Code != http.StatusFound {
736 t.Errorf("/ answered %d", w.Code)
737 } else {
738 pages = append(pages, w.Header().Get("Location")+w.Body.String())
739 }
740 all := strings.Join(pages, "\n")
741 if strings.Contains(all, hidden) != sees {
742 t.Errorf("the reader's pages name %s %v, though the reader sees it %v", hidden, !sees, sees)
743 }
744 for _, unwanted := range []string{">site<", "site,", ", site", "valley:site", "/tools/site/"} {
745 if strings.Contains(all, unwanted) {
746 t.Errorf("the reader's pages hold %q", unwanted)
747 }
748 }
749
750 // The fields beside the target, each by its own shape.
751 for _, want := range []string{
752 `<span class="chip blocked">waits on oc-a000002, a knot in an unpublished project</span>`,
753 } {
754 if !strings.Contains(plan, want) {
755 t.Errorf("the knots page does not show %q", want)
756 }
757 }
758 for target, want := range map[string]string{
759 "/tools/app/knots/oc-a000003": `<li class="mono">a change in an unpublished project</li>`,
760 "/tools/app/knots/bd-a000004": `<dt>Graduated into</dt><dd><a href="/tools/app/knots/oc-a000002">oc-a000002</a></dd>`,
761 "/tools/app/knots/oc-a000006": "<dt>Graduated into</dt><dd>a knot in an unpublished project</dd>",
762 } {
763 if page := h.pageAs(reader, target); !strings.Contains(page, want) {
764 t.Errorf("%s does not show %q", target, want)
765 }
766 }
767 if n := strings.Count(knot, `<span class="muted">a knot in an unpublished project</span>`); n != 2 {
768 t.Errorf("oc-a000003's page names %d blockers as unpublished, not its two", n)
769 }
770 })
771 }
772}
773
774// A reference is read by the whole of a shape its field allows before
775// anything of it is resolved or shown (knot/validate.go): a project's
776// name, <project>:<id>, a knot's ID, or valley:<project>/<change ID>. Here
777// app is anyone's, site is alice's alone, and each value opens with app,
778// which every reader sees, but has none of its field's shapes. Every page
779// that names the field shows it as unpublished, with none of its text,
780// whatever the reader sees, and the projection takes it out of the four
781// derived lists.
782func TestMalformedReferencesNameNothing(t *testing.T) {
783 malformed := []string{"app:site:oc-b000001", "app:oc-b000001:site", "app:site", "app/site", "app:site/oc-b000001"}
784 for _, c := range []struct {
785 field string
786 knot string
787 values []string
788 set func(k *export.Knot, value string)
789 shown map[string]string // a route that names the field, and what it shows there
790 }{
791 {"blocked_by", "oc-a000003", malformed,
792 func(k *export.Knot, v string) { k.BlockedBy = []string{"oc-a000002", v} },
793 map[string]string{"/tools/app/knots/oc-a000003": `<span class="t"><span class="muted">a knot in an unpublished project</span></span>`}},
794 {"target", "oc-a000003", malformed,
795 func(k *export.Knot, v string) { k.Target = v },
796 map[string]string{
797 "/tools/app/knots/oc-a000003": "<dt>Lands in</dt><dd>an unpublished project</dd>",
798 "/-/knots": `<span class="chip quiet">lands in an unpublished project</span>`,
799 }},
800 {"waiting_on", "oc-a000003", malformed,
801 func(k *export.Knot, v string) { k.WaitingOn = []string{"oc-a000002", v} },
802 map[string]string{"/-/knots": `<span class="chip blocked">waits on oc-a000002, a knot in an unpublished project</span>`}},
803 {"graduated_into", "oc-a000006", append([]string{"site", "app:oc-a000002", "bd-a000004", "ida-a000007"}, malformed...),
804 func(k *export.Knot, v string) { k.GraduatedInto = v },
805 map[string]string{"/tools/app/knots/oc-a000006": "<dt>Graduated into</dt><dd>a knot in an unpublished project</dd>"}},
806 {"changes", "oc-a000003", []string{"valley:app/site/secret", "valley:app/site", "valley:app:site",
807 "valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm/site", "valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm site"},
808 func(k *export.Knot, v string) { k.Changes = []string{v} },
809 map[string]string{"/tools/app/knots/oc-a000003": `<li class="mono">a change in an unpublished project</li>`}},
810 } {
811 t.Run(c.field, func(t *testing.T) {
812 h := newHarness(t)
813 e, bundles := h.buildExport(true, nil)
814 h.authorizeReaders(e, map[string][]string{"app": {export.Anyone}, "site": {"alice"}})
815 for i, value := range c.values {
816 next := *e
817 next.Projects = slices.Clone(e.Projects)
818 app := &next.Projects[0]
819 app.Knots = slices.Clone(app.Knots)
820 at := slices.IndexFunc(app.Knots, func(k export.Knot) bool { return k.ID == c.knot })
821 c.set(&app.Knots[at], value)
822 h.publishExport(exporttest.SignedAt.Add(time.Duration(i+1)*time.Minute), &next, bundles)
823 // A bare word is looked for as an element's text, since
824 // the pages' own markup holds words such as site.
825 named := value
826 if !strings.ContainsAny(value, ":/") {
827 named = ">" + value + "<"
828 }
829 for _, reader := range []string{export.Anyone, "bob", "alice"} {
830 for route, want := range c.shown {
831 page := h.pageAs(reader, route)
832 if !strings.Contains(page, want) {
833 t.Errorf("%s = %q: %s as %s does not show %q", c.field, value, route, reader, want)
834 }
835 if strings.Contains(page, named) {
836 t.Errorf("%s = %q: %s as %s names it", c.field, value, route, reader)
837 }
838 }
839 }
840 }
841 })
842 }
843
844 t.Run("derived lists", func(t *testing.T) {
845 h := newHarness(t)
846 e, _ := h.buildExport(true, nil)
847 app := &e.Projects[0]
848 at := slices.IndexFunc(app.Knots, func(k export.Knot) bool { return k.ID == "oc-a000003" })
849 k := &app.Knots[at]
850 k.WaitingOn = append([]string{"oc-a000002"}, malformed...)
851 k.ClearedByEnding, k.Dangling, k.Unresolved = malformed, malformed, malformed
852 for _, shown := range []map[string]bool{{"app": true}, {"app": true, "site": true}} {
853 projected, err := projectForReader(context.Background(), e, shown)
854 if err != nil {
855 t.Fatal(err)
856 }
857 got := projected.Projects[0].Knots[at]
858 if !slices.Equal(got.WaitingOn, []string{"oc-a000002"}) || !got.WaitingOnHidden ||
859 len(got.ClearedByEnding) != 0 || len(got.Dangling) != 0 || len(got.Unresolved) != 0 {
860 t.Errorf("projected for %v, the lists keep %v, %v, %v and %v, and waiting_on_hidden is %v",
861 shown, got.WaitingOn, got.ClearedByEnding, got.Dangling, got.Unresolved, got.WaitingOnHidden)
862 }
863 }
864 })
865}
866
867// The views of what anyone may see have places no named reader's view
868// takes. While every named place holds a view being built, a named
869// reader's request whose view needs another waits, holding no loader
870// slot, no git slot and no generation, and answers 503 at its deadline,
871// or nothing once its reader goes away, leaving no view behind. So does a
872// named reader who may see no more than anyone, though it would share
873// anyone's index. Meanwhile anyone is served, a load of a new generation
874// runs, and the new generation's view of what anyone may see is built and
875// served. Once the builds end, every request that waited for one is
876// served.
877func TestAnonymousViewsSurviveNamedSaturation(t *testing.T) {
878 h := newHarness(t)
879 e, bundles := h.privateViews()
880 h.page("/-/knots")
881
882 hold := make(chan struct{})
883 var holding atomic.Int32
884 h.srv.indexing = func(ctx context.Context, key viewKey) {
885 if strings.Contains(key.projects, "\np") {
886 holding.Add(1)
887 select {
888 case <-hold:
889 case <-ctx.Done():
890 }
891 }
892 }
893 var gitSlots atomic.Int32
894 h.srv.admitted = func() { gitSlots.Add(1) }
895 serve := h.serving
896 var waiting []chan *httptest.ResponseRecorder
897 for i := 1; i <= MaxViews; i++ {
898 waiting = append(waiting, serve(fmt.Sprintf("r%d", i), "/-/knots", context.Background()))
899 }
900 eventually(t, "every named place holds a view being built", func() bool { return holding.Load() == MaxViews })
901
902 // A ninth named view finds no room. It waits holding nothing, and
903 // answers 503 at its deadline; another whose reader goes away answers
904 // nothing. Neither leaves a view or a pin behind.
905 h.srv.timeout = 300 * time.Millisecond
906 h.srv.log = func(error) {}
907 late := serve("r9", "/tools/p1/source/tree/"+h.tip()+"/", context.Background())
908 // The eight wait for their builds, each in a waiting place, and the
909 // ninth waits for room in one more.
910 eventually(t, "the ninth named view waits for room", func() bool { return len(h.srv.loadWaiting) == MaxViews+1 })
911 if h.srv.runningLoads() != 0 || h.srv.heldSlots() != 0 || gitSlots.Load() != 0 {
912 t.Errorf("a request waiting for room holds %d loader slots and %d git slots", h.srv.runningLoads(), h.srv.heldSlots())
913 }
914 select {
915 case w := <-late:
916 if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
917 t.Errorf("a named view that found no room answered %d", w.Code)
918 }
919 case <-time.After(10 * time.Second):
920 t.Fatal("a named view that found no room waited past its deadline")
921 }
922 h.srv.timeout = time.Hour
923 ctx, cancel := context.WithCancel(context.Background())
924 gone := serve("r10", "/-/knots", ctx)
925 eventually(t, "the tenth named view waits for room", func() bool { return len(h.srv.loadWaiting) == MaxViews+1 })
926 cancel()
927 if w := <-gone; w.Body.Len() != 0 {
928 t.Errorf("a request whose reader went away answered %d", w.Code)
929 }
930 if anonymous, named, _ := h.srv.heldViews(); anonymous != 1 || named != MaxViews {
931 t.Errorf("the server holds %d views of what anyone may see and %d others", anonymous, named)
932 }
933
934 // Anyone is served still, from the generation's view, and from the
935 // next generation's, whose export is read and indexed meanwhile. r0,
936 // who may see no more than anyone, shares anyone's index, but takes a
937 // named place for it, so it waits for room.
938 h.page("/-/knots")
939 r0 := serve("r0", "/tools/app/knots/oc-a000002", context.Background())
940 eventually(t, "r0 waits for a named place", func() bool { return len(h.srv.loadWaiting) == MaxViews+1 })
941 app := e.Projects[0]
942 app.Knots = slices.Clone(app.Knots)
943 app.Knots[0].Title = "Readers browse the next plan"
944 next := *e
945 next.Projects = slices.Clone(e.Projects)
946 next.Projects[0] = app
947 h.publishExport(exporttest.SignedAt.Add(2*time.Minute), &next, bundles)
948 if !strings.Contains(h.page("/tools/app/knots/oc-a000001"), "Readers browse the next plan") {
949 t.Error("anyone is not served the next generation while named views fill their places")
950 }
951
952 select {
953 case w := <-r0:
954 t.Errorf("r0 answered %d while every named place was taken", w.Code)
955 default:
956 }
957
958 close(hold)
959 for _, served := range waiting {
960 if w := <-served; w.Code != http.StatusOK {
961 t.Errorf("a named view that was built answered %d", w.Code)
962 }
963 }
964 if w := <-r0; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "/tools/app/knots/oc-a000001") {
965 t.Errorf("r0 answered %d once there was room", w.Code)
966 }
967 if page := h.pageAs("r15", "/-/knots"); !strings.Contains(page, "/tools/p4/knots/") || !strings.Contains(page, "next plan") {
968 t.Error("a named reader is not served the next generation once there is room")
969 }
970 if _, named, pins := h.srv.heldViews(); named > MaxViews || pins != 0 {
971 t.Errorf("the server holds %d named views, pinned %d times", named, pins)
972 }
973 if n := len(h.srv.loadWaiting); n != 0 {
974 t.Errorf("%d requests still hold a place among those that wait", n)
975 }
976}
977
978// A named reader who may see no more than anyone shares anyone's index,
979// but takes a named place for it, and never an anonymous one. Here r0's
980// source requests hold the indexes of what anyone may see of generations
981// A and B while they wait in their git slots, and generation C is
982// activated. An anonymous request for the knots page is served from C at
983// once, while they still hold them. With every other named place held by
984// a view being built, it is served at once too, while r0's request for
985// the knots page of C waits for a named place. Once the named requests
986// let their places go, every request is served.
987func TestNamedRequestsTakeNoAnonymousPlace(t *testing.T) {
988 for _, full := range []bool{false, true} {
989 t.Run(map[bool]string{false: "named places free", true: "named places full"}[full], func(t *testing.T) {
990 h := newHarness(t)
991 e, bundles := h.privateViews()
992 activate := func(at time.Duration, title string) {
993 app := e.Projects[0]
994 app.Knots = slices.Clone(app.Knots)
995 app.Knots[0].Title = title
996 next := *e
997 next.Projects = slices.Clone(e.Projects)
998 next.Projects[0] = app
999 h.publishExport(exporttest.SignedAt.Add(at), &next, bundles)
1000 }
1001 held := make(chan struct{})
1002 var admitted atomic.Int32
1003 h.srv.admitted = func() {
1004 admitted.Add(1)
1005 <-held
1006 }
1007 hold := make(chan struct{})
1008 var holding atomic.Int32
1009 h.srv.indexing = func(ctx context.Context, key viewKey) {
1010 if strings.Contains(key.projects, "\np") {
1011 holding.Add(1)
1012 select {
1013 case <-hold:
1014 case <-ctx.Done():
1015 }
1016 }
1017 }
1018
1019 // r0 holds generation A's index of what anyone may see, and
1020 // then generation B's, each in a request that waits in its
1021 // git slot.
1022 source := "/tools/app/source/tree/" + h.tip() + "/"
1023 named := []chan *httptest.ResponseRecorder{h.serving("r0", source, context.Background())}
1024 eventually(t, "r0 holds generation A's index", func() bool { return admitted.Load() == 1 })
1025 activate(2*time.Minute, "Readers browse plan B")
1026 named = append(named, h.serving("r0", source, context.Background()))
1027 eventually(t, "r0 holds generation B's index", func() bool { return admitted.Load() == 2 })
1028 if anonymous, places, pins := h.srv.heldViews(); anonymous != 0 || places != 2 || pins != 2 {
1029 t.Fatalf("named requests hold %d anonymous places and %d named ones, pinned %d times", anonymous, places, pins)
1030 }
1031 if full {
1032 for i := 1; i <= MaxViews-2; i++ {
1033 named = append(named, h.serving(fmt.Sprintf("r%d", i), "/-/knots", context.Background()))
1034 }
1035 eventually(t, "every named place is taken", func() bool { return holding.Load() == MaxViews-2 })
1036 }
1037
1038 activate(3*time.Minute, "Readers browse plan C")
1039 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
1040 defer cancel()
1041 if w := <-h.serving(export.Anyone, "/-/knots", ctx); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "plan C") {
1042 t.Errorf("an anonymous request for generation C answered %d, %d bytes, while named requests held their places", w.Code, w.Body.Len())
1043 }
1044 late := h.serving("r0", "/-/knots", context.Background())
1045 if full {
1046 eventually(t, "r0 waits for a named place", func() bool { return len(h.srv.namedWaiting) == MaxViews-1 })
1047 time.Sleep(20 * time.Millisecond)
1048 select {
1049 case w := <-late:
1050 t.Errorf("r0 answered %d while every named place was taken", w.Code)
1051 default:
1052 }
1053 }
1054 if admitted.Load() != 2 {
1055 t.Errorf("%d source requests took git slots, not r0's two", admitted.Load())
1056 }
1057
1058 close(hold)
1059 close(held)
1060 for _, served := range append(named, late) {
1061 if w := <-served; w.Code != http.StatusOK {
1062 t.Errorf("a named reader's request answered %d", w.Code)
1063 }
1064 }
1065 if page := h.pageAs("r0", source); !strings.Contains(page, "/tools/app/") {
1066 t.Error("r0 is not served once the places are free")
1067 }
1068 if anonymous, places, pins := h.srv.heldViews(); anonymous > anonymousViews || places > MaxViews || pins != 0 {
1069 t.Errorf("the server holds %d anonymous places and %d named ones, pinned %d times", anonymous, places, pins)
1070 }
1071 if len(h.srv.loadWaiting) != 0 || len(h.srv.namedWaiting) != 0 {
1072 t.Errorf("%d requests, %d of them named, still hold a place among those that wait", len(h.srv.loadWaiting), len(h.srv.namedWaiting))
1073 }
1074 })
1075 }
1076}
1077
1078// Named readers take MaxNamedWaiting of the MaxLoadWaiting places at
1079// most, and the rest are anonymous requests' alone. While every named
1080// place holds a view being built, and named readers' requests wait in
1081// every place they may take, a named reader's request past them answers
1082// 503 at once. A new generation is then activated, and as many anonymous
1083// requests as the places left wait for its load together, and each is
1084// served from it. Once the builds end, every named request that waited is
1085// served.
1086func TestAnonymousRequestsKeepTheirWaitingPlaces(t *testing.T) {
1087 h := newHarness(t)
1088 e, bundles := h.privateViews()
1089 h.page("/-/knots")
1090
1091 hold := make(chan struct{})
1092 var holding atomic.Int32
1093 h.srv.indexing = func(ctx context.Context, key viewKey) {
1094 if strings.Contains(key.projects, "\np") {
1095 holding.Add(1)
1096 select {
1097 case <-hold:
1098 case <-ctx.Done():
1099 }
1100 }
1101 }
1102 var named []chan *httptest.ResponseRecorder
1103 for i := 1; i <= MaxViews; i++ {
1104 named = append(named, h.serving(fmt.Sprintf("r%d", i), "/-/knots", context.Background()))
1105 }
1106 eventually(t, "every named place holds a view being built", func() bool { return holding.Load() == MaxViews })
1107
1108 // Named readers with no room for their views try to take every place
1109 // left. MaxNamedWaiting of them wait, counting the eight, and the rest
1110 // answer 503 at once, well before their deadline.
1111 var refused atomic.Int32
1112 var waited []chan *httptest.ResponseRecorder
1113 for i := range MaxLoadWaiting - MaxViews {
1114 served := h.serving(fmt.Sprintf("r%d", 9+i%7), "/-/knots", context.Background())
1115 answered := make(chan *httptest.ResponseRecorder, 1)
1116 go func() {
1117 w := <-served
1118 if w.Code == http.StatusServiceUnavailable && w.Header().Get("Retry-After") != "" {
1119 refused.Add(1)
1120 }
1121 answered <- w
1122 }()
1123 waited = append(waited, answered)
1124 }
1125 eventually(t, "named readers fill the places they may take", func() bool {
1126 return len(h.srv.namedWaiting) == MaxNamedWaiting && refused.Load() == MaxLoadWaiting-MaxNamedWaiting
1127 })
1128 if n := len(h.srv.loadWaiting); n != MaxNamedWaiting {
1129 t.Fatalf("%d requests wait, not the %d named readers may take", n, MaxNamedWaiting)
1130 }
1131
1132 // A new generation, whose load is held until every anonymous request
1133 // waits for it in a place of its own.
1134 loadHold := make(chan struct{})
1135 h.srv.loading = func(export.Generation) { <-loadHold }
1136 app := e.Projects[0]
1137 app.Knots = slices.Clone(app.Knots)
1138 app.Knots[0].Title = "Readers browse the next plan"
1139 next := *e
1140 next.Projects = slices.Clone(e.Projects)
1141 next.Projects[0] = app
1142 h.publishExport(exporttest.SignedAt.Add(2*time.Minute), &next, bundles)
1143 var anonymous []chan *httptest.ResponseRecorder
1144 for range MaxLoadWaiting - MaxNamedWaiting {
1145 anonymous = append(anonymous, h.serving(export.Anyone, "/tools/app/knots/oc-a000001", context.Background()))
1146 }
1147 eventually(t, "every anonymous request waits for the load", func() bool { return len(h.srv.loadWaiting) == MaxLoadWaiting })
1148 close(loadHold)
1149 for _, served := range anonymous {
1150 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Readers browse the next plan") {
1151 t.Errorf("an anonymous request answered %d, not from the next generation", w.Code)
1152 }
1153 }
1154
1155 close(hold)
1156 answered := 0
1157 for _, served := range append(named, waited...) {
1158 switch w := <-served; w.Code {
1159 case http.StatusOK:
1160 answered++
1161 case http.StatusServiceUnavailable:
1162 default:
1163 t.Errorf("a named reader's request answered %d", w.Code)
1164 }
1165 }
1166 if want := MaxNamedWaiting; answered != want {
1167 t.Errorf("%d named readers' requests were served, not the %d that waited", answered, want)
1168 }
1169 if _, views, pins := h.srv.heldViews(); views > MaxViews || pins != 0 {
1170 t.Errorf("the server holds %d named views, pinned %d times", views, pins)
1171 }
1172 if len(h.srv.loadWaiting) != 0 || len(h.srv.namedWaiting) != 0 {
1173 t.Errorf("%d requests, %d of them named, still hold a place among those that wait", len(h.srv.loadWaiting), len(h.srv.namedWaiting))
1174 }
1175}
1176
1177// A view whose build is stopped, because the last request that waited for
1178// it went away, keeps its place until its worker ends, and no request
1179// takes it again. Here the stopped worker does not notice it was stopped
1180// until it is let go. Meanwhile a request for another view, and one for
1181// the same view, wait for room, and no worker starts beyond the MaxViews
1182// places. Once the stopped worker ends, both are served, and at no time
1183// do more than MaxViews workers build named views.
1184func TestAStoppedBuildKeepsItsPlace(t *testing.T) {
1185 h := newHarness(t)
1186 e, _ := h.privateViews()
1187 h.page("/-/knots")
1188 // r1 alone may read p1 and nothing else.
1189 r1 := projectsKey(e, map[string]bool{"app": true, "p1": true})
1190
1191 release, rest := make(chan struct{}), make(chan struct{})
1192 var live, peak, r1Builds atomic.Int32
1193 h.srv.indexing = func(_ context.Context, key viewKey) {
1194 if !strings.Contains(key.projects, "\np") {
1195 return
1196 }
1197 n := live.Add(1)
1198 defer live.Add(-1)
1199 for p := peak.Load(); n > p && !peak.CompareAndSwap(p, n); p = peak.Load() {
1200 }
1201 if key.projects == r1 && r1Builds.Add(1) == 1 {
1202 <-release
1203 return
1204 }
1205 <-rest
1206 }
1207 ctx, cancel := context.WithCancel(context.Background())
1208 first := h.serving("r1", "/-/knots", ctx)
1209 var others []chan *httptest.ResponseRecorder
1210 for i := 2; i <= MaxViews; i++ {
1211 others = append(others, h.serving(fmt.Sprintf("r%d", i), "/-/knots", context.Background()))
1212 }
1213 eventually(t, "every named place holds a view being built", func() bool { return live.Load() == MaxViews })
1214
1215 // r1 goes away. Its view's build is stopped, though its worker runs on.
1216 cancel()
1217 if w := <-first; w.Body.Len() != 0 {
1218 t.Errorf("a request whose reader went away answered %d", w.Code)
1219 }
1220 if n := h.srv.stoppingViews(); n != 1 {
1221 t.Fatalf("%d stopped views keep their places, not 1", n)
1222 }
1223
1224 // Another reader's view and r1's view again find no room.
1225 another := h.serving("r9", "/-/knots", context.Background())
1226 again := h.serving("r1", "/-/knots", context.Background())
1227 eventually(t, "both requests wait for room", func() bool { return len(h.srv.loadWaiting) == MaxViews+1 })
1228 time.Sleep(20 * time.Millisecond)
1229 if n := live.Load(); n != MaxViews {
1230 t.Errorf("%d workers build named views while a stopped one runs", n)
1231 }
1232
1233 // The stopped worker ends, and gives back its place.
1234 close(release)
1235 eventually(t, "the stopped view gives back its place", func() bool { return h.srv.stoppingViews() == 0 })
1236 close(rest)
1237 for _, served := range append(others, another, again) {
1238 if w := <-served; w.Code != http.StatusOK {
1239 t.Errorf("a named reader's request answered %d", w.Code)
1240 }
1241 }
1242 if p := peak.Load(); p > MaxViews {
1243 t.Errorf("%d workers built named views at once, more than the %d places", p, MaxViews)
1244 }
1245 if _, views, pins := h.srv.heldViews(); views > MaxViews || pins != 0 || h.srv.stoppingViews() != 0 {
1246 t.Errorf("the server holds %d named views, pinned %d times", views, pins)
1247 }
1248}
1249
1250// Loads that only named readers wait for take one of the MaxLoads
1251// workers at most, so a load that an anonymous request waits for always
1252// has one: while one named reader's load runs and another's waits for a
1253// worker, an anonymous request joins the waiting load and starts it.
1254func TestAnonymousRequestsKeepALoader(t *testing.T) {
1255 h := newHarness(t)
1256 var mu sync.Mutex
1257 holds := map[int64]chan struct{}{}
1258 hold := func(seq int64) chan struct{} {
1259 mu.Lock()
1260 defer mu.Unlock()
1261 if holds[seq] == nil {
1262 holds[seq] = make(chan struct{})
1263 }
1264 return holds[seq]
1265 }
1266 var loaded sync.Map
1267 h.srv.loading = func(g export.Generation) {
1268 loaded.Store(g.Sequence, true)
1269 <-hold(g.Sequence)
1270 }
1271 serve := func(reader string) chan *httptest.ResponseRecorder {
1272 served := make(chan *httptest.ResponseRecorder, 1)
1273 go func() { served <- h.as(reader, "GET", "/tools/app/knots/oc-a000001", nil) }()
1274 return served
1275 }
1276 first := h.active()
1277 alice := serve("alice")
1278 eventually(t, "alice's load runs", func() bool { _, ok := loaded.Load(first.Sequence); return ok })
1279 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1280 bob := serve("bob")
1281 eventually(t, "bob waits for a load", func() bool { return len(h.srv.loadWaiting) == 2 })
1282 time.Sleep(20 * time.Millisecond)
1283 if _, ok := loaded.Load(second.Sequence); ok || h.srv.runningLoads() != 1 {
1284 t.Fatalf("a second load that only named readers wait for started, with %d workers", h.srv.runningLoads())
1285 }
1286 anyone := serve(export.Anyone)
1287 eventually(t, "the anonymous request starts the waiting load", func() bool { _, ok := loaded.Load(second.Sequence); return ok })
1288 if len(h.srv.anonLoader) != 1 || len(h.srv.loaders) != 1 {
1289 t.Errorf("the loads hold %d anonymous and %d shared workers", len(h.srv.anonLoader), len(h.srv.loaders))
1290 }
1291 close(hold(second.Sequence))
1292 close(hold(first.Sequence))
1293 for _, served := range []chan *httptest.ResponseRecorder{alice, bob, anyone} {
1294 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "second plan") {
1295 t.Errorf("a request answered %d, not from the second generation", w.Code)
1296 }
1297 }
1298}
1299
1300// holdFirstReads makes the first read of each generation held with hold
1301// wait until the function hold returns is called. reads counts each
1302// generation's reads.
1303func holdFirstReads(h *harness) (hold func(export.Generation) func(), reads func(export.Generation) int) {
1304 var mu sync.Mutex
1305 holds := map[int64]chan struct{}{}
1306 counts := map[int64]int{}
1307 h.srv.loading = func(g export.Generation) {
1308 mu.Lock()
1309 counts[g.Sequence]++
1310 held, first := holds[g.Sequence], counts[g.Sequence] == 1
1311 mu.Unlock()
1312 if first && held != nil {
1313 <-held
1314 }
1315 }
1316 hold = func(g export.Generation) func() {
1317 mu.Lock()
1318 defer mu.Unlock()
1319 held := make(chan struct{})
1320 holds[g.Sequence] = held
1321 return func() { close(held) }
1322 }
1323 reads = func(g export.Generation) int {
1324 mu.Lock()
1325 defer mu.Unlock()
1326 return counts[g.Sequence]
1327 }
1328 return hold, reads
1329}
1330
1331// When the last anonymous request leaves a load on the kept loader while
1332// a named reader still waits for it, and the other loader is free, the
1333// load moves to the other loader and runs on: the kept loader is free for
1334// the next anonymous request at once, and the export is read only once.
1335func TestALoadAnonymousRequestsLeaveMovesToTheOtherLoader(t *testing.T) {
1336 h := newHarness(t)
1337 hold, reads := holdFirstReads(h)
1338 const target = "/tools/app/knots/oc-a000001"
1339 first := h.active()
1340 letFirstGo := hold(first)
1341 ctx, cancel := context.WithCancel(context.Background())
1342 anyone := h.serving(export.Anyone, target, ctx)
1343 eventually(t, "the anonymous request's load runs", func() bool { return reads(first) == 1 })
1344 if len(h.srv.anonLoader) != 1 {
1345 t.Fatal("the anonymous request's load does not run on the kept loader")
1346 }
1347 bob := h.serving("bob", target, context.Background())
1348 eventually(t, "bob joins the load", func() bool { a, n := h.srv.loadWaiters(); return a == 1 && n == 1 })
1349
1350 cancel()
1351 if w := <-anyone; w.Body.Len() != 0 {
1352 t.Errorf("a request whose reader went away answered %d", w.Code)
1353 }
1354 if len(h.srv.anonLoader) != 0 || len(h.srv.loaders) != 1 {
1355 t.Errorf("the load holds %d kept and %d other loaders, not the other alone", len(h.srv.anonLoader), len(h.srv.loaders))
1356 }
1357 if a, n := h.srv.loadWaiters(); a != 0 || n != 1 {
1358 t.Errorf("%d anonymous and %d named requests wait for loads, not bob alone", a, n)
1359 }
1360
1361 // While bob's load runs on, an anonymous request for a newer
1362 // generation is read on the kept loader and served.
1363 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1364 if w := h.as(export.Anyone, "GET", target, nil); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "second plan") {
1365 t.Errorf("an anonymous request answered %d, not from the second generation", w.Code)
1366 }
1367 letFirstGo()
1368 if w := <-bob; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "second plan") {
1369 t.Errorf("bob's request answered %d, not from the second generation", w.Code)
1370 }
1371 if n := reads(first); n != 1 {
1372 t.Errorf("the first generation was read %d times, not once", n)
1373 }
1374 eventually(t, "every loader is given back", func() bool { return h.srv.runningLoads() == 0 })
1375}
1376
1377// When the last anonymous request leaves a load on the kept loader while
1378// a named reader still waits for it, and the other loader runs a named
1379// reader's load, the load is stopped and the kept loader is free at once,
1380// though the stopped worker has not ended. Here alice's load of the first
1381// generation holds the other loader. An anonymous request starts the
1382// second generation's load on the kept loader, bob joins it, and the
1383// anonymous request goes away. bob waits for a load again. Then either a
1384// third generation is activated, and an anonymous request for it is
1385// served while alice's load and the stopped worker still run, or alice's
1386// load ends, and bob's load takes the other loader. Every request is
1387// served, and once every worker has ended the loads hold no loader.
1388func TestALoadAnonymousRequestsLeaveGivesBackTheKeptLoader(t *testing.T) {
1389 const target = "/tools/app/knots/oc-a000001"
1390 stopped := func(t *testing.T) (h *harness, letFirstGo, letSecondGo func(), alice, bob chan *httptest.ResponseRecorder, reads func(export.Generation) int, second export.Generation) {
1391 h = newHarness(t)
1392 var hold func(export.Generation) func()
1393 hold, reads = holdFirstReads(h)
1394 first := h.active()
1395 letFirstGo = hold(first)
1396 alice = h.serving("alice", target, context.Background())
1397 eventually(t, "alice's load runs", func() bool { return reads(first) == 1 })
1398 if len(h.srv.loaders) != 1 {
1399 t.Fatal("alice's load does not run on the other loader")
1400 }
1401
1402 second = h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1403 letSecondGo = hold(second)
1404 ctx, cancel := context.WithCancel(context.Background())
1405 anyone := h.serving(export.Anyone, target, ctx)
1406 eventually(t, "the anonymous request's load runs", func() bool { return reads(second) == 1 })
1407 bob = h.serving("bob", target, context.Background())
1408 eventually(t, "bob joins the load", func() bool { a, n := h.srv.loadWaiters(); return a == 1 && n == 2 })
1409
1410 cancel()
1411 if w := <-anyone; w.Body.Len() != 0 {
1412 t.Errorf("a request whose reader went away answered %d", w.Code)
1413 }
1414 if len(h.srv.anonLoader) != 0 || len(h.srv.loaders) != 1 {
1415 t.Errorf("the loads hold %d kept and %d other loaders, not the other alone", len(h.srv.anonLoader), len(h.srv.loaders))
1416 }
1417 eventually(t, "bob waits for a load again", func() bool { a, n := h.srv.loadWaiters(); return a == 0 && n == 2 })
1418 return
1419 }
1420 expect := func(t *testing.T, title string, served ...chan *httptest.ResponseRecorder) {
1421 t.Helper()
1422 for _, w := range served {
1423 if w := <-w; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
1424 t.Errorf("a request answered %d, not with %q", w.Code, title)
1425 }
1426 }
1427 }
1428
1429 t.Run("an anonymous request for a newer generation", func(t *testing.T) {
1430 h, letFirstGo, letSecondGo, alice, bob, _, _ := stopped(t)
1431 h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1432 if w := h.as(export.Anyone, "GET", target, nil); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "third plan") {
1433 t.Errorf("the anonymous request answered %d, not from the third generation", w.Code)
1434 }
1435 letFirstGo()
1436 letSecondGo()
1437 expect(t, "Readers browse the third plan", alice, bob)
1438 eventually(t, "every loader is given back", func() bool { return h.srv.runningLoads() == 0 })
1439 })
1440
1441 t.Run("the other loader comes free", func(t *testing.T) {
1442 h, letFirstGo, letSecondGo, alice, bob, reads, second := stopped(t)
1443 letFirstGo()
1444 expect(t, "Readers browse the second plan", alice, bob)
1445 if n := reads(second); n != 2 {
1446 t.Errorf("the second generation was read %d times, not by the stopped load and bob's", n)
1447 }
1448 letSecondGo()
1449 eventually(t, "every loader is given back", func() bool { return h.srv.runningLoads() == 0 })
1450 })
1451}
1452
1453// A response a named reader was rendered is written only under the
1454// authorization it was rendered under. One whose grant is withdrawn while
1455// it renders, a Markdown page, an archive, a knot or a redirect, is
1456// rendered again under the new authorization, and answers the one 404.
1457func TestANamedReadersResponseIsHeldToTheAuthorization(t *testing.T) {
1458 for _, path := range []string{"/tools/site/source/blob/%s/README.md", "/tools/site/source/archive/%s.tar.gz",
1459 "/tools/site/knots/oc-b000001", "/site/", "/tools/site/source/tree/%s/"} {
1460 t.Run(path, func(t *testing.T) {
1461 h := newHarness(t)
1462 e := h.edge(exporttest.SignedAt.Add(time.Minute), map[string][]string{"app": {export.Anyone}, "site": {"alice"}})
1463 siteTip := git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef)
1464 target := strings.ReplaceAll(path, "%s", siteTip)
1465 if w := h.as("alice", "GET", target, nil); w.Code != http.StatusOK && w.Code != http.StatusPermanentRedirect {
1466 t.Fatalf("GET %s as alice answered %d", target, w.Code)
1467 }
1468 missing := h.as("alice", "GET", "/tools/nosuch/", nil)
1469 renders := 0
1470 h.srv.checked = func() {
1471 if renders++; renders == 1 {
1472 h.authorizeReaders(e, map[string][]string{"app": {export.Anyone}})
1473 }
1474 }
1475 w := h.as("alice", "GET", target, nil)
1476 if w.Code != http.StatusNotFound || !bytes.Equal(w.Body.Bytes(), missing.Body.Bytes()) || w.Header().Get("Location") != "" {
1477 t.Errorf("GET %s withdrawn while it rendered answered %d, to %q", target, w.Code, w.Header().Get("Location"))
1478 }
1479 if renders != 2 {
1480 t.Errorf("GET %s rendered %d times, want twice", target, renders)
1481 }
1482 })
1483 }
1484}