| 1 | package server |
| 2 | |
| 3 | import ( |
| 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 | "strings" |
| 21 | "sync" |
| 22 | "sync/atomic" |
| 23 | "syscall" |
| 24 | "testing" |
| 25 | "time" |
| 26 | |
| 27 | "the-valley/knot" |
| 28 | "the-valley/webui/export" |
| 29 | "the-valley/webui/export/exporttest" |
| 30 | ) |
| 31 | |
| 32 | // harness is a server over a real store that the fixture's export was |
| 33 | // uploaded to, with a clock the test sets. |
| 34 | type harness struct { |
| 35 | t *testing.T |
| 36 | f *exporttest.Fixture |
| 37 | store *export.Store |
| 38 | srv *Server |
| 39 | now time.Time |
| 40 | } |
| 41 | |
| 42 | // newHarness serves the fixture's export, two minutes after it was |
| 43 | // collected. |
| 44 | func newHarness(t *testing.T) *harness { |
| 45 | t.Helper() |
| 46 | f := exporttest.New(t) |
| 47 | store, err := export.OpenStore(t.TempDir(), func(err error) { t.Errorf("the store reported: %v", err) }) |
| 48 | if err != nil { |
| 49 | t.Fatal(err) |
| 50 | } |
| 51 | f.Upload(t, store) |
| 52 | h := &harness{t: t, f: f, store: store, now: exporttest.Collected.Add(2 * time.Minute)} |
| 53 | h.srv = New(Config{Store: store, Now: func() time.Time { return h.now }, |
| 54 | Log: func(err error) { t.Errorf("the server logged: %v", err) }}) |
| 55 | return h |
| 56 | } |
| 57 | |
| 58 | func (h *harness) do(method, target string) *httptest.ResponseRecorder { |
| 59 | h.t.Helper() |
| 60 | w := httptest.NewRecorder() |
| 61 | h.srv.ServeHTTP(w, httptest.NewRequest(method, target, nil)) |
| 62 | return w |
| 63 | } |
| 64 | |
| 65 | func (h *harness) get(target string) *httptest.ResponseRecorder { |
| 66 | h.t.Helper() |
| 67 | return h.do("GET", target) |
| 68 | } |
| 69 | |
| 70 | // page is the body of a GET that must answer 200. |
| 71 | func (h *harness) page(target string) string { |
| 72 | h.t.Helper() |
| 73 | w := h.get(target) |
| 74 | if w.Code != http.StatusOK { |
| 75 | h.t.Fatalf("GET %s answered %d:\n%s", target, w.Code, w.Body) |
| 76 | } |
| 77 | return w.Body.String() |
| 78 | } |
| 79 | |
| 80 | // tip is the fixture's published source tip of app. |
| 81 | func (h *harness) tip() string { return h.f.Export.Projects[0].SourceTip } |
| 82 | |
| 83 | // publish activates a new generation, signed at: the fixture's export |
| 84 | // changed by change, with the bundles given in place of the fixture's. |
| 85 | func (h *harness) publish(at time.Time, bundles map[string]string, change func(*export.Export)) export.Generation { |
| 86 | t := h.t |
| 87 | t.Helper() |
| 88 | e, err := export.Decode(h.f.ExportJSON) |
| 89 | if err != nil { |
| 90 | t.Fatal(err) |
| 91 | } |
| 92 | change(e) |
| 93 | data, err := e.Encode() |
| 94 | if err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | paths := map[string]string{} |
| 98 | for name, path := range h.f.Bundles { |
| 99 | paths[name] = path |
| 100 | } |
| 101 | for name, path := range bundles { |
| 102 | paths[name] = path |
| 103 | } |
| 104 | bodies := map[string]export.Body{} |
| 105 | for name, path := range paths { |
| 106 | if bodies[name], err = export.FileBody(name, path); err != nil { |
| 107 | t.Fatal(err) |
| 108 | } |
| 109 | } |
| 110 | m, err := export.NewManifest(exporttest.Instance, exporttest.Destination, at.UnixNano(), e, data, bodies) |
| 111 | if err != nil { |
| 112 | t.Fatal(err) |
| 113 | } |
| 114 | hw, err := h.store.HighWater() |
| 115 | if err != nil { |
| 116 | t.Fatal(err) |
| 117 | } |
| 118 | a := h.f.Admission() |
| 119 | a.Now, a.HighWater = at.Add(time.Second), hw |
| 120 | if m, err = export.VerifyManifest(bytes.NewReader(h.f.Sign(t, m)), a); err != nil { |
| 121 | t.Fatal(err) |
| 122 | } |
| 123 | st, err := h.store.Stage(m) |
| 124 | if err != nil { |
| 125 | t.Fatal(err) |
| 126 | } |
| 127 | inv, err := h.store.Inventory(st) |
| 128 | if err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | for _, need := range inv.Needs { |
| 132 | body := data |
| 133 | if need.Name != export.ExportFile { |
| 134 | if body, err = os.ReadFile(paths[need.Name]); err != nil { |
| 135 | t.Fatal(err) |
| 136 | } |
| 137 | } |
| 138 | req := httptest.NewRequest("PUT", export.BodyPath(m.Sequence, need.SHA256), bytes.NewReader(body)) |
| 139 | if _, err := export.StageBody(st.Bodies(), export.Body{Name: need.Name, SHA256: need.SHA256, Size: need.Size}, 64<<20, req); err != nil { |
| 140 | t.Fatal(err) |
| 141 | } |
| 142 | } |
| 143 | g, err := h.store.Activate(context.Background(), st) |
| 144 | if err != nil { |
| 145 | t.Fatal(err) |
| 146 | } |
| 147 | return g |
| 148 | } |
| 149 | |
| 150 | // active is the generation the store serves. |
| 151 | func (h *harness) active() export.Generation { |
| 152 | h.t.Helper() |
| 153 | g, release, err := h.store.Open() |
| 154 | if err != nil { |
| 155 | h.t.Fatal(err) |
| 156 | } |
| 157 | release() |
| 158 | return g |
| 159 | } |
| 160 | |
| 161 | // git runs git on the repository at repo, with no configuration of the |
| 162 | // caller's and a fixed identity for the commits it writes. |
| 163 | func git(t *testing.T, repo string, stdin []byte, args ...string) string { |
| 164 | t.Helper() |
| 165 | cmd := exec.Command(export.GitProgram, append([]string{"--git-dir=" + repo}, args...)...) |
| 166 | for _, kv := range os.Environ() { |
| 167 | if !strings.HasPrefix(kv, "GIT_") { |
| 168 | cmd.Env = append(cmd.Env, kv) |
| 169 | } |
| 170 | } |
| 171 | cmd.Env = append(cmd.Env, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", |
| 172 | "GIT_AUTHOR_NAME=Example Author", "GIT_AUTHOR_EMAIL=author@example.org", "GIT_AUTHOR_DATE=1791190800 +0000", |
| 173 | "GIT_COMMITTER_NAME=Example Author", "GIT_COMMITTER_EMAIL=author@example.org", "GIT_COMMITTER_DATE=1791190800 +0000") |
| 174 | if stdin != nil { |
| 175 | cmd.Stdin = bytes.NewReader(stdin) |
| 176 | } |
| 177 | var stderr bytes.Buffer |
| 178 | cmd.Stderr = &stderr |
| 179 | out, err := cmd.Output() |
| 180 | if err != nil { |
| 181 | t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, stderr.String()) |
| 182 | } |
| 183 | return strings.TrimSpace(string(out)) |
| 184 | } |
| 185 | |
| 186 | // section is the part of a page from one marker up to the next. |
| 187 | func 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. |
| 200 | func 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's plan", "1 of 5 done", |
| 221 | "Unfiled", "Render Markdown in a later slice", |
| 222 | "waits on oc-a000002", |
| 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="/knots/app/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{"/knots/site/", "/source/site/", "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 | // unpublishedText is what of the hidden project site the fixture's |
| 265 | // references hold: its name and its knots' IDs. No page shows any of it. |
| 266 | var unpublishedText = []string{"site:", "oc-b000001", "oc-b000002", "lands in site", ">site<", "valley:site"} |
| 267 | |
| 268 | // A knot's page shows its body and comments, and marks the edited |
| 269 | // comment. A reference into a hidden project is shown as unpublished, |
| 270 | // with nothing of its text, and a missing knot of a public project is |
| 271 | // named as missing. |
| 272 | func TestKnotPage(t *testing.T) { |
| 273 | h := newHarness(t) |
| 274 | page := h.page("/knots/app/oc-a000002") |
| 275 | for _, want := range []string{ |
| 276 | "Each milestone is listed with its progress.", |
| 277 | "Start with the milestones that have open children.", |
| 278 | "Claimed; the change is ready for approval.", |
| 279 | `<span class="chip quiet">edited</span><span>2026-10-25 10:30 UTC by agent</span>`, |
| 280 | `<a href="/knots/app/oc-a000001">Readers browse the app's plan</a>`, |
| 281 | } { |
| 282 | if !strings.Contains(page, want) { |
| 283 | t.Errorf("the knot's page does not show %q", want) |
| 284 | } |
| 285 | } |
| 286 | if n := strings.Count(page, ">edited<"); n != 1 { |
| 287 | t.Errorf("%d comments are marked edited; one was edited", n) |
| 288 | } |
| 289 | |
| 290 | page = h.page("/knots/app/oc-a000003") |
| 291 | if !strings.Contains(page, `<a href="/knots/app/oc-a000002">The plan page lists milestones</a>`) { |
| 292 | t.Error("the local blocker is not linked") |
| 293 | } |
| 294 | for _, want := range []string{ |
| 295 | `<span class="nochild"></span><span class="t"><span class="muted">a knot in an unpublished project</span></span>`, |
| 296 | "<dt>Lands in</dt><dd>an unpublished project</dd>", |
| 297 | } { |
| 298 | if !strings.Contains(page, want) { |
| 299 | t.Errorf("the knot's page does not show %q", want) |
| 300 | } |
| 301 | } |
| 302 | page += h.page("/knots/app/bd-a000004") |
| 303 | if !strings.Contains(page, "<dt>Lands in</dt><dd>a knot in an unpublished project</dd>") { |
| 304 | t.Error("a target in the hidden project is not shown as unpublished") |
| 305 | } |
| 306 | for _, unwanted := range append([]string{"/knots/site/", "/source/site/"}, unpublishedText...) { |
| 307 | if strings.Contains(page, unwanted) { |
| 308 | t.Errorf("the knot's page shows %q", unwanted) |
| 309 | } |
| 310 | } |
| 311 | if w := h.get("/knots/app/oc-fffffff"); w.Code != http.StatusNotFound { |
| 312 | t.Errorf("a missing knot answered %d", w.Code) |
| 313 | } |
| 314 | |
| 315 | // A knot of a public project the graph does not hold, and a local |
| 316 | // knot that is not there, are named as missing. A change of the |
| 317 | // hidden project is not named. |
| 318 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) { |
| 319 | for i := range e.Projects[0].Knots { |
| 320 | if k := &e.Projects[0].Knots[i]; k.ID == "oc-a000003" { |
| 321 | k.BlockedBy = append(k.BlockedBy, "app:oc-fffffff", "oc-eeeeeee") |
| 322 | k.Edges = append(k.Edges, export.Edge{Field: "blocked_by", Ref: "app:oc-fffffff", Project: "app", ID: "oc-fffffff", State: export.EdgeDangling}) |
| 323 | k.Changes = append(k.Changes, "valley:site/kmnopqrstuvwxyzkmnopqrstuvwxyzkm", "valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm") |
| 324 | } |
| 325 | } |
| 326 | }) |
| 327 | page = h.page("/knots/app/oc-a000003") |
| 328 | for _, want := range []string{ |
| 329 | `<span class="mono">app:oc-fffffff</span> <span class="muted">not found in its graph</span>`, |
| 330 | `<span class="mono">oc-eeeeeee</span> <span class="muted">not found</span>`, |
| 331 | `<li class="mono">a change in an unpublished project</li>`, |
| 332 | `<li class="mono">valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm</li>`, |
| 333 | } { |
| 334 | if !strings.Contains(page, want) { |
| 335 | t.Errorf("the knot's page does not show %q", want) |
| 336 | } |
| 337 | } |
| 338 | for _, unwanted := range unpublishedText { |
| 339 | if strings.Contains(page, unwanted) { |
| 340 | t.Errorf("the knot's page shows %q", unwanted) |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | // A project the export does not hold as public answers every route |
| 346 | // exactly as a project that does not exist, even when its repository is |
| 347 | // in the generation's directory. |
| 348 | func TestHiddenProjectAnswersLikeMissing(t *testing.T) { |
| 349 | h := newHarness(t) |
| 350 | g := h.active() |
| 351 | if err := os.CopyFS(filepath.Join(g.Dir, "repos", "site.git"), os.DirFS(h.f.Repos["site"])); err != nil { |
| 352 | t.Fatal(err) |
| 353 | } |
| 354 | siteTip := git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef) |
| 355 | notFound := h.get("/knots/app/oc-fffffff") |
| 356 | for _, route := range []string{ |
| 357 | "/knots/%s/oc-b000001", |
| 358 | "/source/%s", |
| 359 | "/source/%s/", |
| 360 | "/source/%s/tree/" + siteTip + "/", |
| 361 | "/source/%s/blob/" + siteTip + "/README.md", |
| 362 | "/source/%s/log/" + siteTip, |
| 363 | "/source/%s/tree/" + siteTip + "/no/such/path/", |
| 364 | "/source/%s/anything", |
| 365 | } { |
| 366 | hidden, missing := h.get(fmt.Sprintf(route, "site")), h.get(fmt.Sprintf(route, "nosuch")) |
| 367 | if hidden.Code != http.StatusNotFound || missing.Code != http.StatusNotFound { |
| 368 | t.Errorf("%s answered %d hidden and %d missing", route, hidden.Code, missing.Code) |
| 369 | } |
| 370 | if fmt.Sprint(hidden.Header()) != fmt.Sprint(missing.Header()) { |
| 371 | t.Errorf("%s answered with other headers hidden than missing:\n%v\n%v", route, hidden.Header(), missing.Header()) |
| 372 | } |
| 373 | if !bytes.Equal(hidden.Body.Bytes(), missing.Body.Bytes()) || !bytes.Equal(hidden.Body.Bytes(), notFound.Body.Bytes()) { |
| 374 | t.Errorf("%s answered with another page hidden than missing", route) |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | // A source route serves a commit only when main's published tip reaches |
| 380 | // it, and refuses every other object ID or name with the one 404. |
| 381 | func TestUnreachableCommitIsRefused(t *testing.T) { |
| 382 | h := newHarness(t) |
| 383 | repo, _ := h.active().Repo("app") |
| 384 | tip := h.tip() |
| 385 | tree := git(t, repo, nil, "rev-parse", tip+"^{tree}") |
| 386 | readme := git(t, repo, nil, "rev-parse", tip+":README.md") |
| 387 | side := git(t, repo, nil, "commit-tree", tree, "-p", tip, "-m", "a commit main does not reach") |
| 388 | parent := git(t, repo, nil, "rev-parse", tip+"~2") |
| 389 | notFound := h.get("/knots/app/oc-fffffff").Body.String() |
| 390 | |
| 391 | for _, commit := range []string{side, tree, readme, tip[:12], "main", "HEAD", strings.Repeat("0", 40), tip + "~1"} { |
| 392 | for _, route := range []string{"/source/app/tree/%s/", "/source/app/blob/%s/README.md", "/source/app/log/%s"} { |
| 393 | target := fmt.Sprintf(route, commit) |
| 394 | w := h.get(target) |
| 395 | if w.Code != http.StatusNotFound || w.Body.String() != notFound { |
| 396 | t.Errorf("GET %s answered %d, not the one 404", target, w.Code) |
| 397 | } |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | // A commit the tip reaches is served, as that commit had it. |
| 402 | page := h.page("/source/app/blob/" + parent + "/README.md") |
| 403 | if !strings.Contains(page, "A synthetic project for the web UI's tests.") || strings.Contains(page, "readme") { |
| 404 | t.Errorf("the first README is not served as the first commit had it:\n%s", page) |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | // The source browser lists a directory and its README, shows a file and |
| 409 | // main's log, and every source link names its project, a full commit and |
| 410 | // a path. |
| 411 | func TestSourceBrowser(t *testing.T) { |
| 412 | h := newHarness(t) |
| 413 | tip := h.tip() |
| 414 | |
| 415 | w := h.get("/source/app/") |
| 416 | if w.Code != http.StatusFound || w.Header().Get("Location") != "/source/app/tree/"+tip+"/" { |
| 417 | t.Fatalf("the project's source answered %d to %q", w.Code, w.Header().Get("Location")) |
| 418 | } |
| 419 | |
| 420 | root := h.page("/source/app/tree/" + tip + "/") |
| 421 | docs, src, readme := strings.Index(root, ">docs/<"), strings.Index(root, ">src/<"), strings.Index(root, ">README.md<") |
| 422 | if docs < 0 || src < 0 || readme < 0 || readme < src || src < docs { |
| 423 | t.Errorf("the root does not list docs/ and src/ before README.md:\n%s", root) |
| 424 | } |
| 425 | if !strings.Contains(root, `<pre class="text"># app`) { |
| 426 | t.Error("the root does not show its README") |
| 427 | } |
| 428 | if dir := h.page("/source/app/tree/" + tip + "/docs/"); !strings.Contains(dir, ">guide.md<") { |
| 429 | t.Error("docs/ does not list guide.md") |
| 430 | } |
| 431 | file := h.page("/source/app/blob/" + tip + "/docs/guide.md") |
| 432 | if !strings.Contains(file, `<tr id="L1"><td class="ln"><a href="#L1">1</a></td><td class="src"># Guide</td></tr>`) { |
| 433 | t.Errorf("the file is not shown line by line:\n%s", file) |
| 434 | } |
| 435 | log := h.page("/source/app/log/" + tip) |
| 436 | first, last := strings.Index(log, "docs: a guide, and the README names it"), strings.Index(log, "app: the first README") |
| 437 | if first < 0 || last < first { |
| 438 | t.Errorf("the log does not list main's commits newest first:\n%s", log) |
| 439 | } |
| 440 | |
| 441 | links := regexp.MustCompile(`href="(/source/[^"]*)"`) |
| 442 | named := regexp.MustCompile(`^/source/app/(tree|blob|log)/[0-9a-f]{40}(/|$)`) |
| 443 | for _, page := range []string{root, file, log} { |
| 444 | for _, m := range links.FindAllStringSubmatch(page, -1) { |
| 445 | if !named.MatchString(m[1]) { |
| 446 | t.Errorf("the link %s names no commit", m[1]) |
| 447 | } |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | for _, target := range []string{ |
| 452 | "/source/app/tree/" + tip + "/README.md/", |
| 453 | "/source/app/blob/" + tip + "/docs", |
| 454 | "/source/app/blob/" + tip + "/docs/guide.md/", |
| 455 | "/source/app/blob/" + tip + "/docs/../README.md", |
| 456 | "/source/app/blob/" + tip + "/docs%2Fguide.md", |
| 457 | "/source/app/tree/" + tip + "//", |
| 458 | "/source/app/log/" + tip + "?skip=-1", |
| 459 | } { |
| 460 | if w := h.get(target); w.Code != http.StatusNotFound { |
| 461 | t.Errorf("GET %s answered %d", target, w.Code) |
| 462 | } |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | // file is one file a test commits: its mode, path and content. |
| 467 | type file struct{ mode, path, content string } |
| 468 | |
| 469 | // commitMain writes a commit onto the fixture's app main, with message, |
| 470 | // that holds the files given beside what main holds. It returns the new |
| 471 | // tip and a bundle of it. Each content is written once, however many |
| 472 | // files hold it. |
| 473 | func (h *harness) commitMain(message string, files ...file) (tip, bundle string) { |
| 474 | t := h.t |
| 475 | t.Helper() |
| 476 | repo := h.f.Repos["app"] |
| 477 | var b bytes.Buffer |
| 478 | data := func(s string) { fmt.Fprintf(&b, "data %d\n%s\n", len(s), s) } |
| 479 | marks := map[string]int{} |
| 480 | for _, f := range files { |
| 481 | if _, ok := marks[f.content]; !ok { |
| 482 | marks[f.content] = len(marks) + 1 |
| 483 | fmt.Fprintf(&b, "blob\nmark :%d\n", marks[f.content]) |
| 484 | data(f.content) |
| 485 | } |
| 486 | } |
| 487 | who := "Example Author <author@example.org> 1791190800 +0000" |
| 488 | fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who) |
| 489 | data(message) |
| 490 | fmt.Fprintf(&b, "from %s\n", git(t, repo, nil, "rev-parse", export.MainRef)) |
| 491 | for _, f := range files { |
| 492 | fmt.Fprintf(&b, "M %s :%d %s\n", f.mode, marks[f.content], f.path) |
| 493 | } |
| 494 | git(t, repo, b.Bytes(), "fast-import", "--quiet") |
| 495 | tip = git(t, repo, nil, "rev-parse", export.MainRef) |
| 496 | bundle = filepath.Join(t.TempDir(), "app.bundle") |
| 497 | git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main") |
| 498 | return tip, bundle |
| 499 | } |
| 500 | |
| 501 | // publishMain activates a generation whose app main is tip, carried by |
| 502 | // bundle. |
| 503 | func (h *harness) publishMain(at time.Time, tip, bundle string) { |
| 504 | h.t.Helper() |
| 505 | h.publish(at, map[string]string{"app": bundle}, func(e *export.Export) { e.Projects[0].SourceTip = tip }) |
| 506 | } |
| 507 | |
| 508 | // hostileMain writes a commit onto the fixture's app main that holds a |
| 509 | // file of HTML, a file larger than a page shows, a binary file, a file |
| 510 | // whose name is HTML, and a symbolic link out of the repository. It |
| 511 | // returns the new tip and a bundle of it. |
| 512 | func (h *harness) hostileMain() (tip, bundle string) { |
| 513 | return h.commitMain("hostile: <script>alert(\"subject\")</script>\n", |
| 514 | file{"100644", "page.html", "<html><script>alert(\"file\")</script><img src=x onerror=alert(2)></html>\n"}, |
| 515 | file{"100644", "big.txt", strings.Repeat("big\n", (MaxFile/4)+1)}, |
| 516 | file{"100644", "binary.bin", "\x7fELF\x00\x01\x02<script>alert(\"binary\")</script>"}, |
| 517 | file{"100644", "<img src=x onerror=alert(3)>.txt", "named\n"}, |
| 518 | file{"120000", "link", "../../etc/passwd"}, |
| 519 | ) |
| 520 | } |
| 521 | |
| 522 | // HTML, scripts, large files and binary files from a repository or the |
| 523 | // plan render inert: escaped as text, or not shown. |
| 524 | func TestHostileContentRendersInert(t *testing.T) { |
| 525 | h := newHarness(t) |
| 526 | tip, bundle := h.hostileMain() |
| 527 | h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) { |
| 528 | e.Projects[0].SourceTip = tip |
| 529 | }) |
| 530 | |
| 531 | inert := func(target, page string, wants ...string) { |
| 532 | t.Helper() |
| 533 | // Escaped, a tag is text; only a tag the page did not escape, or |
| 534 | // an attribute it let a value break out into, is active. |
| 535 | for _, active := range []string{"<script", "<img", `" onerror`, "\x00"} { |
| 536 | if strings.Contains(page, active) { |
| 537 | t.Errorf("GET %s holds %q", target, active) |
| 538 | } |
| 539 | } |
| 540 | for _, want := range wants { |
| 541 | if !strings.Contains(page, want) { |
| 542 | t.Errorf("GET %s does not show %q", target, want) |
| 543 | } |
| 544 | } |
| 545 | } |
| 546 | at := "/source/app/tree/" + tip + "/" |
| 547 | inert(at, h.page(at), |
| 548 | `<script>alert("readme")</script>`, |
| 549 | `<img src=x onerror=alert(3)>.txt`, |
| 550 | `href="/source/app/blob/`+tip+`/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"`) |
| 551 | at = "/source/app/blob/" + tip + "/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt" |
| 552 | inert(at, h.page(at), ">named<") |
| 553 | at = "/source/app/blob/" + tip + "/page.html" |
| 554 | inert(at, h.page(at), `<html><script>alert("file")</script><img src=x onerror=alert(2)></html>`) |
| 555 | at = "/source/app/blob/" + tip + "/big.txt" |
| 556 | page := h.page(at) |
| 557 | inert(at, page, "This file is 1.0 MiB, larger than the 1.0 MiB a page shows.") |
| 558 | if len(page) > 64<<10 { |
| 559 | t.Errorf("the large file's page is %d bytes", len(page)) |
| 560 | } |
| 561 | at = "/source/app/blob/" + tip + "/binary.bin" |
| 562 | inert(at, h.page(at), "This file is binary, 39 bytes, and is not shown.") |
| 563 | at = "/source/app/blob/" + tip + "/link" |
| 564 | inert(at, h.page(at), "A symbolic link to ../../etc/passwd. It is not followed.") |
| 565 | at = "/source/app/log/" + tip |
| 566 | inert(at, h.page(at), "hostile: <script>alert("subject")</script>") |
| 567 | |
| 568 | at = "/knots/app/bd-a000004" |
| 569 | inert(at, h.page(at), |
| 570 | `A README holding <script>alert("knot")</script> must show as text.`, |
| 571 | `Also <img src=x onerror=alert(1)> in a comment.`) |
| 572 | } |
| 573 | |
| 574 | // A directory larger than a page reads is listed in part, and a commit |
| 575 | // message larger than a page reads ends its page of history early. git |
| 576 | // is stopped once its listing passes MaxRead, and nothing past a record's |
| 577 | // bound is kept. |
| 578 | func TestOversizedTreeAndHistory(t *testing.T) { |
| 579 | h := newHarness(t) |
| 580 | // Each entry of huge/ takes 308 bytes of git ls-tree's output, so |
| 581 | // 15,000 of them pass MaxRead at about entry 13,600. |
| 582 | longest := "!" + strings.Repeat("l", 4095) |
| 583 | files := []file{{"100644", "huge/" + longest, "x\n"}} |
| 584 | name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) } |
| 585 | for i := range 15_000 { |
| 586 | files = append(files, file{"100644", "huge/" + name(i), "x\n"}) |
| 587 | } |
| 588 | if n := 15_000 * (6 + 1 + 4 + 1 + 40 + 1 + 7 + 1 + 246 + 1); n <= MaxRead { |
| 589 | t.Fatalf("the listing of huge/ is %d bytes, within MaxRead", n) |
| 590 | } |
| 591 | h.commitMain("app: a directory larger than a page reads\n", files...) |
| 592 | h.commitMain("long: " + strings.Repeat("a long subject ", (100<<10)/15) + "\n") |
| 593 | tip, bundle := h.commitMain("longer: " + strings.Repeat("a subject past the bound ", (5<<20)/25) + "\n") |
| 594 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 595 | |
| 596 | at := "/source/app/tree/" + tip + "/huge/" |
| 597 | page := h.page(at) |
| 598 | if !strings.Contains(page, "This directory is larger than a page reads, so only part of it is listed.") { |
| 599 | t.Error("huge/ is not marked as listed in part") |
| 600 | } |
| 601 | if n := strings.Count(page, `<tr><td class="name">`); n != MaxEntries { |
| 602 | t.Errorf("huge/ lists %d entries, not %d", n, MaxEntries) |
| 603 | } |
| 604 | if !strings.Contains(page, `">`+longest+`</a>`) { |
| 605 | t.Error("the entry with the longest name git accepts is not listed whole") |
| 606 | } |
| 607 | if len(page) > 1<<20 { |
| 608 | t.Errorf("huge/'s page is %d bytes", len(page)) |
| 609 | } |
| 610 | if w := h.get("/source/app/blob/" + tip + "/huge/" + name(0)); w.Code != http.StatusOK { |
| 611 | t.Errorf("an entry read before MaxRead answered %d", w.Code) |
| 612 | } |
| 613 | if w := h.get("/source/app/blob/" + tip + "/huge/" + name(14_999)); w.Code != http.StatusNotFound { |
| 614 | t.Errorf("an entry past MaxRead answered %d", w.Code) |
| 615 | } |
| 616 | |
| 617 | at = "/source/app/log/" + tip |
| 618 | page = h.page(at) |
| 619 | if !strings.Contains(page, "This page ends early: its commits are larger than a page reads.") { |
| 620 | t.Error("the page of history holding a 5 MiB message does not end early") |
| 621 | } |
| 622 | if n := strings.Count(page, `<tr><td class="name">`); n != 1 { |
| 623 | t.Errorf("the page that ends early lists %d commits, not the one it cut", n) |
| 624 | } |
| 625 | if m := regexp.MustCompile(`<td>(longer: a subject past the bound[^<]*)…</td>`).FindStringSubmatch(page); m == nil || len(m[1]) > maxLogText { |
| 626 | t.Error("the cut commit's subject is not shown cut to maxLogText") |
| 627 | } |
| 628 | if !strings.Contains(page, `href="/source/app/log/`+tip+`?skip=1"`) { |
| 629 | t.Error("the page that ends early does not link the commits after the one it cut") |
| 630 | } |
| 631 | page = h.page(at + "?skip=1") |
| 632 | if strings.Contains(page, "ends early") || !strings.Contains(page, "long: a long subject") || !strings.Contains(page, "app: the first README") { |
| 633 | t.Errorf("the next page of history is not whole:\n%s", page) |
| 634 | } |
| 635 | if strings.Contains(page, strings.Repeat("a long subject ", (maxLogText/15)+1)) { |
| 636 | t.Error("a subject longer than a page shows is not cut") |
| 637 | } |
| 638 | for _, p := range []string{at, at + "?skip=1"} { |
| 639 | if n := len(h.page(p)); n > 64<<10 { |
| 640 | t.Errorf("GET %s is %d bytes", p, n) |
| 641 | } |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | // A file of exactly MaxFile bytes of newlines is shown to MaxLines lines, |
| 646 | // and its page says where it stops. A README longer than a page shows is |
| 647 | // shown in part. |
| 648 | func TestLongFileIsShownInPart(t *testing.T) { |
| 649 | h := newHarness(t) |
| 650 | tip, bundle := h.commitMain("app: long files\n", |
| 651 | file{"100644", "newlines.txt", strings.Repeat("\n", MaxFile)}, |
| 652 | file{"100644", "long/README.md", strings.Repeat("a line of the README\n", 2*MaxLines)}, |
| 653 | file{"100644", "wide.txt", strings.Repeat("<", MaxFile)}, |
| 654 | ) |
| 655 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 656 | |
| 657 | page := h.page("/source/app/blob/" + tip + "/newlines.txt") |
| 658 | last := fmt.Sprintf(`id="L%d"`, MaxLines) |
| 659 | if !strings.Contains(page, last) || strings.Contains(page, fmt.Sprintf(`id="L%d"`, MaxLines+1)) { |
| 660 | t.Errorf("the file of newlines is not shown to line %d", MaxLines) |
| 661 | } |
| 662 | if want := fmt.Sprintf("The page stops at line %d of %d.", MaxLines, MaxFile); !strings.Contains(page, want) { |
| 663 | t.Errorf("the page does not say %q", want) |
| 664 | } |
| 665 | if len(page) > MaxShown { |
| 666 | t.Errorf("the page of a file of newlines is %d bytes, past MaxShown", len(page)) |
| 667 | } |
| 668 | |
| 669 | // One line of MaxFile characters that each escape to four bytes is |
| 670 | // cut where MaxShown is reached. |
| 671 | page = h.page("/source/app/blob/" + tip + "/wide.txt") |
| 672 | if !strings.Contains(page, "The page stops at line 1 of 1.") || len(page) > MaxShown+64<<10 { |
| 673 | t.Errorf("the page of one wide line is %d bytes", len(page)) |
| 674 | } |
| 675 | |
| 676 | page = h.page("/source/app/tree/" + tip + "/long/") |
| 677 | if !strings.Contains(page, "This README is longer than a page shows, and only its start is shown.") { |
| 678 | t.Error("the long README is not marked as shown in part") |
| 679 | } |
| 680 | if n := strings.Count(page, "a line of the README"); n != MaxLines { |
| 681 | t.Errorf("the long README shows %d lines, not %d", n, MaxLines) |
| 682 | } |
| 683 | } |
| 684 | |
| 685 | // A chain of knots as deep as the graph's knot limit allows renders its |
| 686 | // milestone to MaxPlanDepth levels, counts every knot under it, and |
| 687 | // names MaxPlanDepth parents in the deepest knot's trail. The plan page's |
| 688 | // structure is built once for the generation. Siblings that block one |
| 689 | // another in a cycle share the last stage of their path. |
| 690 | func TestDeepPlan(t *testing.T) { |
| 691 | h := newHarness(t) |
| 692 | var chain []string |
| 693 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) { |
| 694 | p := &e.Projects[0] |
| 695 | for i := range knot.MaxKnots - len(p.Knots) - 3 { |
| 696 | id := fmt.Sprintf("oc-c%06x", i) |
| 697 | k := export.Knot{ID: id, Type: "outcome", Status: "open", Active: true, State: "ready", |
| 698 | Title: fmt.Sprintf("Level %d of the chain", i), Created: "2026-10-01", CreatedBy: "operator"} |
| 699 | if i == 0 { |
| 700 | p.Roots = append(p.Roots, id) |
| 701 | } else { |
| 702 | k.Parent = chain[i-1] |
| 703 | p.Knots[len(p.Knots)-1].Children = []string{id} |
| 704 | } |
| 705 | chain = append(chain, id) |
| 706 | p.Knots = append(p.Knots, k) |
| 707 | } |
| 708 | // Under the first link, a path whose two last siblings wait on |
| 709 | // each other. |
| 710 | free, a, b := "oc-d000001", "oc-d000002", "oc-d000003" |
| 711 | for _, k := range []export.Knot{ |
| 712 | {ID: free, BlockedBy: []string{}}, |
| 713 | {ID: a, BlockedBy: []string{free, b}}, |
| 714 | {ID: b, BlockedBy: []string{a}}, |
| 715 | } { |
| 716 | k.Type, k.Status, k.State, k.Title, k.Parent = "outcome", "open", "blocked", "Sibling "+k.ID, chain[0] |
| 717 | p.Knots = append(p.Knots, k) |
| 718 | } |
| 719 | for i := range p.Knots { |
| 720 | if p.Knots[i].ID == chain[0] { |
| 721 | p.Knots[i].Children = append(p.Knots[i].Children, free, a, b) |
| 722 | } |
| 723 | } |
| 724 | }) |
| 725 | |
| 726 | page := h.page("/") |
| 727 | if want := fmt.Sprintf("%d of %d done", 0, len(chain)-1+3); !strings.Contains(page, want) { |
| 728 | t.Errorf("the chain's milestone does not count every knot under it as %q", want) |
| 729 | } |
| 730 | if !strings.Contains(page, `href="/knots/app/`+chain[MaxPlanDepth]+`"`) || strings.Contains(page, `href="/knots/app/`+chain[MaxPlanDepth+1]+`"`) { |
| 731 | t.Errorf("the chain's tree is not shown to %d levels", MaxPlanDepth) |
| 732 | } |
| 733 | if n := strings.Count(page, ">more on its page<"); n != 1 { |
| 734 | t.Errorf("%d rows say there is more on their page; the chain's deepest shown row does", n) |
| 735 | } |
| 736 | if len(page) > 256<<10 { |
| 737 | t.Errorf("the plan page is %d bytes", len(page)) |
| 738 | } |
| 739 | paths := section(t, page, `id="paths-h"`, `id="ms-h"`) |
| 740 | stage := regexp.MustCompile(`<span class="stage-num">(\d+)</span><ul class="plain">(.*?)</ul>`) |
| 741 | var stages []string |
| 742 | for _, m := range stage.FindAllStringSubmatch(paths, -1) { |
| 743 | if strings.Contains(m[2], "Sibling") { |
| 744 | var ids []string |
| 745 | for _, id := range regexp.MustCompile(`"mono muted">(oc-d00000\d)<`).FindAllStringSubmatch(m[2], -1) { |
| 746 | ids = append(ids, id[1]) |
| 747 | } |
| 748 | stages = append(stages, m[1]+":"+strings.Join(ids, ",")) |
| 749 | } |
| 750 | } |
| 751 | if got := strings.Join(stages, " "); got != "1:oc-d000001 2:oc-d000002,oc-d000003" { |
| 752 | t.Errorf("the siblings' path has stages %q", got) |
| 753 | } |
| 754 | |
| 755 | h.srv.mu.Lock() |
| 756 | plan := h.srv.cached.idx.plan |
| 757 | h.srv.mu.Unlock() |
| 758 | h.page("/") |
| 759 | h.srv.mu.Lock() |
| 760 | again := h.srv.cached.idx.plan |
| 761 | h.srv.mu.Unlock() |
| 762 | if plan != again { |
| 763 | t.Error("the plan page's structure was built again for the same generation") |
| 764 | } |
| 765 | |
| 766 | deepest := chain[len(chain)-1] |
| 767 | page = h.page("/knots/app/" + deepest) |
| 768 | trail := section(t, page, `<nav class="trail"`, `</nav>`) |
| 769 | if n := strings.Count(trail, `<a href="/knots/`); n != MaxPlanDepth || !strings.Contains(trail, "<span>…</span>") { |
| 770 | t.Errorf("the deepest knot's trail names %d parents, or does not mark those above them", n) |
| 771 | } |
| 772 | if !strings.Contains(trail, chain[len(chain)-2]) || strings.Contains(trail, `"/knots/app/`+chain[len(chain)-2-MaxPlanDepth]+`"`) { |
| 773 | t.Error("the trail does not name the nearest parents alone") |
| 774 | } |
| 775 | } |
| 776 | |
| 777 | // Every response carries the strict policy, and the policy admits the |
| 778 | // page's one inline stylesheet and one inline script by their hashes and |
| 779 | // nothing from another origin. |
| 780 | func TestEveryResponseCarriesTheCSP(t *testing.T) { |
| 781 | h := newHarness(t) |
| 782 | for _, c := range []struct{ method, target string }{ |
| 783 | {"GET", "/"}, |
| 784 | {"GET", "/knots/app/oc-a000002"}, |
| 785 | {"GET", "/source/app/"}, |
| 786 | {"GET", "/source/app/tree/" + h.tip() + "/"}, |
| 787 | {"GET", "/source/app/blob/" + h.tip() + "/README.md"}, |
| 788 | {"GET", "/no/such/page"}, |
| 789 | {"POST", "/"}, |
| 790 | {"HEAD", "/"}, |
| 791 | } { |
| 792 | w := h.do(c.method, c.target) |
| 793 | got := w.Header().Get("Content-Security-Policy") |
| 794 | if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" { |
| 795 | t.Errorf("%s %s answered with policy %q", c.method, c.target, got) |
| 796 | } |
| 797 | } |
| 798 | for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} { |
| 799 | if !strings.Contains(csp, directive) { |
| 800 | t.Errorf("the policy lacks %s", directive) |
| 801 | } |
| 802 | } |
| 803 | for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} { |
| 804 | if strings.Contains(csp, loose) { |
| 805 | t.Errorf("the policy holds %q", loose) |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | page := h.page("/") |
| 810 | inline := func(tag string) string { |
| 811 | t.Helper() |
| 812 | m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1) |
| 813 | if len(m) != 1 || strings.Count(page, "<"+tag) != 1 { |
| 814 | t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag) |
| 815 | } |
| 816 | sum := sha256.Sum256([]byte(m[0][1])) |
| 817 | return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'" |
| 818 | } |
| 819 | if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") { |
| 820 | t.Errorf("the policy does not admit the page's script, %s", hash) |
| 821 | } |
| 822 | if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") { |
| 823 | t.Errorf("the policy does not admit the page's stylesheet, %s", hash) |
| 824 | } |
| 825 | for _, external := range []string{"<link", " src=", "@import", "url("} { |
| 826 | if strings.Contains(page, external) { |
| 827 | t.Errorf("the plan page holds %q", external) |
| 828 | } |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | // A request serves everything from the generation it opened, though |
| 833 | // another activates while it runs, and that generation outlives the |
| 834 | // activation until the request releases it. |
| 835 | func TestARequestKeepsItsGeneration(t *testing.T) { |
| 836 | h := newHarness(t) |
| 837 | paused, resume := make(chan export.Generation), make(chan struct{}) |
| 838 | var once sync.Once |
| 839 | h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) } |
| 840 | served := make(chan *httptest.ResponseRecorder) |
| 841 | go func() { |
| 842 | w := httptest.NewRecorder() |
| 843 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/knots/app/oc-a000001", nil)) |
| 844 | served <- w |
| 845 | }() |
| 846 | old := <-paused |
| 847 | |
| 848 | next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 849 | if next.Sequence == old.Sequence { |
| 850 | t.Fatal("the publish did not activate a new generation") |
| 851 | } |
| 852 | if _, err := os.Stat(old.Dir); err != nil { |
| 853 | t.Fatalf("the generation a request holds was deleted: %v", err) |
| 854 | } |
| 855 | close(resume) |
| 856 | w := <-served |
| 857 | if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app's plan") || strings.Contains(body, "second plan") { |
| 858 | t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body) |
| 859 | } |
| 860 | if !strings.Contains(h.page("/knots/app/oc-a000001"), "Readers browse the second plan") { |
| 861 | t.Error("the next request does not serve the new generation") |
| 862 | } |
| 863 | |
| 864 | // Released, the old generation goes with the next activation. |
| 865 | h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan")) |
| 866 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 867 | t.Errorf("the released generation is still on disk: %v", err) |
| 868 | } |
| 869 | } |
| 870 | |
| 871 | // eventually waits up to ten seconds for cond to hold. |
| 872 | func eventually(t *testing.T, what string, cond func() bool) { |
| 873 | t.Helper() |
| 874 | for deadline := time.Now().Add(10 * time.Second); !cond(); time.Sleep(time.Millisecond) { |
| 875 | if time.Now().After(deadline) { |
| 876 | t.Fatalf("timed out waiting until %s", what) |
| 877 | } |
| 878 | } |
| 879 | } |
| 880 | |
| 881 | // renamed changes the title of the fixture's first knot. |
| 882 | func renamed(title string) func(*export.Export) { |
| 883 | return func(e *export.Export) { e.Projects[0].Knots[0].Title = title } |
| 884 | } |
| 885 | |
| 886 | // Requests that wait for a generation together read its export once. |
| 887 | // While it is read, a newer generation is read on its own, and at most |
| 888 | // MaxLoads exports are read at once. A request whose load ends after a |
| 889 | // newer generation was activated waits for that one, so every request is |
| 890 | // served the generation active when its snapshot is ready, and an older |
| 891 | // read that finishes last does not displace the newest snapshot. |
| 892 | func TestExportLoadsCoalesce(t *testing.T) { |
| 893 | h := newHarness(t) |
| 894 | var mu sync.Mutex |
| 895 | loads := map[int64]int{} |
| 896 | holds := map[int64]chan struct{}{} |
| 897 | hold := func(g export.Generation) chan struct{} { |
| 898 | mu.Lock() |
| 899 | defer mu.Unlock() |
| 900 | if holds[g.Sequence] == nil { |
| 901 | holds[g.Sequence] = make(chan struct{}) |
| 902 | } |
| 903 | return holds[g.Sequence] |
| 904 | } |
| 905 | h.srv.loading = func(g export.Generation) { |
| 906 | mu.Lock() |
| 907 | loads[g.Sequence]++ |
| 908 | mu.Unlock() |
| 909 | <-hold(g) |
| 910 | } |
| 911 | loaded := func(g export.Generation) int { |
| 912 | mu.Lock() |
| 913 | defer mu.Unlock() |
| 914 | return loads[g.Sequence] |
| 915 | } |
| 916 | var opens atomic.Int32 |
| 917 | h.srv.opened = func(export.Generation) { opens.Add(1) } |
| 918 | get := func(n int) chan *httptest.ResponseRecorder { |
| 919 | served := make(chan *httptest.ResponseRecorder, n) |
| 920 | for range n { |
| 921 | go func() { |
| 922 | w := httptest.NewRecorder() |
| 923 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/knots/app/oc-a000001", nil)) |
| 924 | served <- w |
| 925 | }() |
| 926 | } |
| 927 | return served |
| 928 | } |
| 929 | expect := func(served chan *httptest.ResponseRecorder, n int, title string) { |
| 930 | t.Helper() |
| 931 | for range n { |
| 932 | if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) { |
| 933 | t.Errorf("a request answered %d, not with %q", w.Code, title) |
| 934 | } |
| 935 | } |
| 936 | } |
| 937 | waiting := func(n int) func() bool { return func() bool { return len(h.srv.loadWaiting) == n } } |
| 938 | |
| 939 | first := h.active() |
| 940 | firstServed := get(10) |
| 941 | eventually(t, "ten requests wait for the first generation's read", func() bool { |
| 942 | return loaded(first) == 1 && len(h.srv.loadWaiting) == 10 |
| 943 | }) |
| 944 | second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 945 | secondServed := get(1) |
| 946 | eventually(t, "the second generation is read", func() bool { return loaded(second) == 1 }) |
| 947 | |
| 948 | // Both loaders are taken, so the third generation waits for one. |
| 949 | third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan")) |
| 950 | thirdServed := get(1) |
| 951 | eventually(t, "a request waits for the third generation", waiting(12)) |
| 952 | time.Sleep(20 * time.Millisecond) |
| 953 | if n := loaded(third); n != 0 { |
| 954 | t.Errorf("a third export was read while %d were", MaxLoads) |
| 955 | } |
| 956 | if n := opens.Load(); n != 0 { |
| 957 | t.Errorf("%d requests opened a generation while they waited for its read", n) |
| 958 | } |
| 959 | |
| 960 | // The second read ends, and its request finds the third generation |
| 961 | // active, and waits for that read with the third's request. |
| 962 | close(hold(second)) |
| 963 | eventually(t, "the third generation is read", func() bool { return loaded(third) == 1 }) |
| 964 | close(hold(third)) |
| 965 | expect(secondServed, 1, "Readers browse the third plan") |
| 966 | expect(thirdServed, 1, "Readers browse the third plan") |
| 967 | close(hold(first)) |
| 968 | expect(firstServed, 10, "Readers browse the third plan") |
| 969 | |
| 970 | if !strings.Contains(h.page("/knots/app/oc-a000001"), "Readers browse the third plan") { |
| 971 | t.Error("the first generation's read displaced the third's") |
| 972 | } |
| 973 | for _, g := range []export.Generation{first, second, third} { |
| 974 | if n := loaded(g); n != 1 { |
| 975 | t.Errorf("generation %d's export was read %d times", g.Sequence, n) |
| 976 | } |
| 977 | } |
| 978 | } |
| 979 | |
| 980 | // Source requests past MaxGit wait, MaxWaiting of them, and one more |
| 981 | // answers 503 at once. A waiting request holds no generation, so an |
| 982 | // activation while the server is saturated deletes the old generation, |
| 983 | // and every waiting request serves the new one. A request's time runs |
| 984 | // from its arrival, so one that waits past it answers 503. |
| 985 | func TestSourceAdmission(t *testing.T) { |
| 986 | h := newHarness(t) |
| 987 | var admitted atomic.Int32 |
| 988 | release := make(chan struct{}) |
| 989 | h.srv.admitted = func() { |
| 990 | admitted.Add(1) |
| 991 | <-release |
| 992 | } |
| 993 | target := "/source/app/tree/" + h.tip() + "/" |
| 994 | get := func(n int) chan *httptest.ResponseRecorder { |
| 995 | served := make(chan *httptest.ResponseRecorder, n) |
| 996 | for range n { |
| 997 | go func() { |
| 998 | w := httptest.NewRecorder() |
| 999 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", target, nil)) |
| 1000 | served <- w |
| 1001 | }() |
| 1002 | } |
| 1003 | return served |
| 1004 | } |
| 1005 | |
| 1006 | old := h.active() |
| 1007 | served := get(MaxGit + MaxWaiting) |
| 1008 | eventually(t, "every slot is taken and MaxWaiting requests wait", func() bool { |
| 1009 | return admitted.Load() == MaxGit && len(h.srv.waiting) == MaxWaiting |
| 1010 | }) |
| 1011 | if w := h.get(target); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 1012 | t.Errorf("a source request past MaxWaiting answered %d, Retry-After %q", w.Code, w.Header().Get("Retry-After")) |
| 1013 | } |
| 1014 | h.page("/") // a page that runs no git is served still |
| 1015 | |
| 1016 | tip, bundle := h.commitMain("app: a commit while the server is saturated\n", file{"100644", "saturated.txt", "saturated\n"}) |
| 1017 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1018 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 1019 | t.Errorf("a generation no request had opened outlived the activation: %v", err) |
| 1020 | } |
| 1021 | close(release) |
| 1022 | for range MaxGit + MaxWaiting { |
| 1023 | if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "/source/app/tree/"+tip+"/") { |
| 1024 | t.Errorf("a waiting request answered %d, not from the new generation", w.Code) |
| 1025 | } |
| 1026 | } |
| 1027 | |
| 1028 | // A request that waits past its time answers 503. Those that held |
| 1029 | // the slots meanwhile ran out of time too. |
| 1030 | h.srv.timeout = 200 * time.Millisecond |
| 1031 | h.srv.log = func(error) {} |
| 1032 | admitted.Store(0) |
| 1033 | release = make(chan struct{}) |
| 1034 | held := get(MaxGit) |
| 1035 | eventually(t, "every slot is taken", func() bool { return admitted.Load() == MaxGit }) |
| 1036 | start := time.Now() |
| 1037 | if w := h.get(target); w.Code != http.StatusServiceUnavailable { |
| 1038 | t.Errorf("a request that waited past its time answered %d", w.Code) |
| 1039 | } |
| 1040 | if waited := time.Since(start); waited > 5*time.Second { |
| 1041 | t.Errorf("a request waited %v past its time of 200ms", waited) |
| 1042 | } |
| 1043 | close(release) |
| 1044 | for range MaxGit { |
| 1045 | if w := <-held; w.Code != http.StatusServiceUnavailable { |
| 1046 | t.Errorf("a request that ran out of time answered %d", w.Code) |
| 1047 | } |
| 1048 | } |
| 1049 | } |
| 1050 | |
| 1051 | // stallingListener accepts connections whose writes stall until release |
| 1052 | // is closed, while stall is set. Each sends on stalled the first time one |
| 1053 | // of its writes stalls. |
| 1054 | type stallingListener struct { |
| 1055 | net.Listener |
| 1056 | stall atomic.Bool |
| 1057 | release chan struct{} |
| 1058 | stalled chan struct{} |
| 1059 | } |
| 1060 | |
| 1061 | func (l *stallingListener) Accept() (net.Conn, error) { |
| 1062 | c, err := l.Listener.Accept() |
| 1063 | if err != nil || !l.stall.Load() { |
| 1064 | return c, err |
| 1065 | } |
| 1066 | return &stallingConn{Conn: c, l: l}, nil |
| 1067 | } |
| 1068 | |
| 1069 | type stallingConn struct { |
| 1070 | net.Conn |
| 1071 | l *stallingListener |
| 1072 | once sync.Once |
| 1073 | } |
| 1074 | |
| 1075 | func (c *stallingConn) Write(p []byte) (int, error) { |
| 1076 | c.once.Do(func() { c.l.stalled <- struct{}{} }) |
| 1077 | <-c.l.release |
| 1078 | return c.Conn.Write(p) |
| 1079 | } |
| 1080 | |
| 1081 | // Readers that never read their responses hold no git slot and no |
| 1082 | // generation: more of them than MaxGit and MaxWaiting together are |
| 1083 | // stalled writing, and a new reader is still served, and an activation |
| 1084 | // deletes the generation they were served from. |
| 1085 | func TestSlowReadersHoldNothing(t *testing.T) { |
| 1086 | h := newHarness(t) |
| 1087 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 1088 | if err != nil { |
| 1089 | t.Fatal(err) |
| 1090 | } |
| 1091 | n := MaxGit + MaxWaiting + 4 |
| 1092 | sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)} |
| 1093 | sl.stall.Store(true) |
| 1094 | srv := &http.Server{Handler: h.srv} |
| 1095 | go srv.Serve(sl) |
| 1096 | var conns []net.Conn |
| 1097 | defer func() { |
| 1098 | close(sl.release) |
| 1099 | for _, c := range conns { |
| 1100 | c.Close() |
| 1101 | } |
| 1102 | srv.Close() |
| 1103 | }() |
| 1104 | |
| 1105 | old := h.active() |
| 1106 | target := "/source/app/blob/" + h.tip() + "/docs/guide.md" |
| 1107 | for range n { |
| 1108 | c, err := net.Dial("tcp", ln.Addr().String()) |
| 1109 | if err != nil { |
| 1110 | t.Fatal(err) |
| 1111 | } |
| 1112 | conns = append(conns, c) |
| 1113 | fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target) |
| 1114 | } |
| 1115 | for i := range n { |
| 1116 | select { |
| 1117 | case <-sl.stalled: |
| 1118 | case <-time.After(10 * time.Second): |
| 1119 | t.Fatalf("%d of %d slow readers' responses were written; the rest wait", i, n) |
| 1120 | } |
| 1121 | } |
| 1122 | sl.stall.Store(false) |
| 1123 | if len(h.srv.slots) != 0 || len(h.srv.waiting) != 0 { |
| 1124 | t.Errorf("slow readers hold %d git slots, and %d requests wait", len(h.srv.slots), len(h.srv.waiting)) |
| 1125 | } |
| 1126 | |
| 1127 | client := &http.Client{Timeout: 10 * time.Second} |
| 1128 | resp, err := client.Get("http://" + ln.Addr().String() + target) |
| 1129 | if err != nil { |
| 1130 | t.Fatal(err) |
| 1131 | } |
| 1132 | resp.Body.Close() |
| 1133 | if resp.StatusCode != http.StatusOK { |
| 1134 | t.Errorf("a new reader answered %d while slow readers stall", resp.StatusCode) |
| 1135 | } |
| 1136 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(*export.Export) {}) |
| 1137 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 1138 | t.Errorf("the generation slow readers were served from outlived the activation: %v", err) |
| 1139 | } |
| 1140 | } |
| 1141 | |
| 1142 | // Before the first activation the server says nothing is published, and |
| 1143 | // it answers GET and HEAD alone. |
| 1144 | func TestNothingPublishedAndMethods(t *testing.T) { |
| 1145 | store, err := export.OpenStore(t.TempDir(), nil) |
| 1146 | if err != nil { |
| 1147 | t.Fatal(err) |
| 1148 | } |
| 1149 | srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }}) |
| 1150 | w := httptest.NewRecorder() |
| 1151 | srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil)) |
| 1152 | if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") { |
| 1153 | t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body) |
| 1154 | } |
| 1155 | |
| 1156 | h := newHarness(t) |
| 1157 | for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} { |
| 1158 | w := h.do(method, "/") |
| 1159 | if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" { |
| 1160 | t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow")) |
| 1161 | } |
| 1162 | } |
| 1163 | } |
| 1164 | |
| 1165 | // tooLarge checks that GET target answers with the one short page that |
| 1166 | // says a page is too large. |
| 1167 | func (h *harness) tooLarge(target string) { |
| 1168 | h.t.Helper() |
| 1169 | w := h.get(target) |
| 1170 | if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) { |
| 1171 | 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()) |
| 1172 | } |
| 1173 | if n := len(h.srv.budget); n != 0 { |
| 1174 | h.t.Errorf("GET %s kept %d pieces of the budget", target, n) |
| 1175 | } |
| 1176 | } |
| 1177 | |
| 1178 | // A response's body is at most MaxResponse bytes. A page that would pass |
| 1179 | // the bound answers with the one short page that says it is too large, |
| 1180 | // and the failure is logged: a knot whose body passes MaxResponse, and, |
| 1181 | // under a smaller bound, a file, a directory, a page of history and the |
| 1182 | // plan page. A page within the bound is served on each route. |
| 1183 | func TestPageTooLarge(t *testing.T) { |
| 1184 | h := newHarness(t) |
| 1185 | var logged []string |
| 1186 | h.srv.log = func(err error) { logged = append(logged, err.Error()) } |
| 1187 | files := []file{{"100644", "wide.txt", strings.Repeat("<", 16<<10)}} |
| 1188 | for i := range 32 { |
| 1189 | files = append(files, file{"100644", fmt.Sprintf("wide/%02d-%s", i, strings.Repeat("n", 1000)), "x\n"}) |
| 1190 | } |
| 1191 | h.commitMain("app: a wide file and a wide directory\n", files...) |
| 1192 | var tip, bundle string |
| 1193 | for i := range 8 { |
| 1194 | tip, bundle = h.commitMain(fmt.Sprintf("%d %s\n", i, strings.Repeat(`"`, maxLogText))) |
| 1195 | } |
| 1196 | h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) { |
| 1197 | p := &e.Projects[0] |
| 1198 | p.SourceTip = tip |
| 1199 | p.Knots[0].Body = strings.Repeat("a", MaxResponse) |
| 1200 | for i := range 100 { |
| 1201 | p.Knots = append(p.Knots, export.Knot{ID: fmt.Sprintf("oc-e%06x", i), Type: "outcome", Status: "open", |
| 1202 | Active: true, State: "ready", Title: strings.Repeat(`"`, knot.MaxTitle), Created: "2026-10-01", CreatedBy: "operator"}) |
| 1203 | } |
| 1204 | }) |
| 1205 | |
| 1206 | h.tooLarge("/knots/app/" + h.f.Export.Projects[0].Knots[0].ID) |
| 1207 | h.page("/knots/app/oc-a000002") |
| 1208 | |
| 1209 | h.srv.maxResponse = 32 << 10 |
| 1210 | at := "/source/app/blob/" + tip + "/" |
| 1211 | h.tooLarge(at + "wide.txt") |
| 1212 | h.page(at + "docs/guide.md") |
| 1213 | at = "/source/app/tree/" + tip + "/" |
| 1214 | h.tooLarge(at + "wide/") |
| 1215 | h.page(at + "docs/") |
| 1216 | h.tooLarge("/source/app/log/" + tip) |
| 1217 | h.page("/source/app/log/" + tip + "?skip=8") |
| 1218 | h.tooLarge("/") |
| 1219 | |
| 1220 | if len(logged) != 5 { |
| 1221 | t.Errorf("%d failures were logged for 5 pages too large: %q", len(logged), logged) |
| 1222 | } |
| 1223 | for _, l := range logged { |
| 1224 | if !strings.Contains(l, "larger than") { |
| 1225 | t.Errorf("the server logged %q", l) |
| 1226 | } |
| 1227 | } |
| 1228 | if len(tooLargePage) > 16<<10 { |
| 1229 | t.Errorf("the page that says a page is too large is %d bytes", len(tooLargePage)) |
| 1230 | } |
| 1231 | } |
| 1232 | |
| 1233 | // Rendered responses share a budget of MaxBuffered bytes, which each |
| 1234 | // holds from when it starts rendering until it is written. Readers that |
| 1235 | // never read, asking for twice the budget in all, hold no more than it: |
| 1236 | // once their pages fill it, a page it has no room for answers 503 at |
| 1237 | // once, and a small page that fits is still served. The server's heap |
| 1238 | // grows by no more than the budget, and the budget is whole again once |
| 1239 | // the readers read. |
| 1240 | func TestSlowReadersShareTheBudget(t *testing.T) { |
| 1241 | h := newHarness(t) |
| 1242 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) { |
| 1243 | e.Projects[0].Knots[0].Body = strings.Repeat("a line of a long body\n", (4<<20)/22) |
| 1244 | }) |
| 1245 | target := "/knots/app/" + h.f.Export.Projects[0].Knots[0].ID |
| 1246 | size := len(h.page(target)) |
| 1247 | pieces := (size + pieceSize - 1) / pieceSize |
| 1248 | fit := cap(h.srv.budget) / pieces |
| 1249 | n := 2*MaxBuffered/size + 1 |
| 1250 | |
| 1251 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 1252 | if err != nil { |
| 1253 | t.Fatal(err) |
| 1254 | } |
| 1255 | sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)} |
| 1256 | sl.stall.Store(true) |
| 1257 | srv := &http.Server{Handler: h.srv} |
| 1258 | go srv.Serve(sl) |
| 1259 | var conns []net.Conn |
| 1260 | released := false |
| 1261 | defer func() { |
| 1262 | if !released { |
| 1263 | close(sl.release) |
| 1264 | } |
| 1265 | for _, c := range conns { |
| 1266 | c.Close() |
| 1267 | } |
| 1268 | srv.Close() |
| 1269 | }() |
| 1270 | |
| 1271 | var before runtime.MemStats |
| 1272 | runtime.GC() |
| 1273 | runtime.ReadMemStats(&before) |
| 1274 | // One reader at a time, each stalled before the next asks, so the |
| 1275 | // readers that fill the budget are the first fit of them. |
| 1276 | for i := range n { |
| 1277 | c, err := net.Dial("tcp", ln.Addr().String()) |
| 1278 | if err != nil { |
| 1279 | t.Fatal(err) |
| 1280 | } |
| 1281 | conns = append(conns, c) |
| 1282 | fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target) |
| 1283 | select { |
| 1284 | case <-sl.stalled: |
| 1285 | case <-time.After(10 * time.Second): |
| 1286 | t.Fatalf("reader %d of %d was not answered", i+1, n) |
| 1287 | } |
| 1288 | } |
| 1289 | sl.stall.Store(false) |
| 1290 | var after runtime.MemStats |
| 1291 | runtime.GC() |
| 1292 | runtime.ReadMemStats(&after) |
| 1293 | if held := len(h.srv.budget); held != fit*pieces { |
| 1294 | t.Errorf("slow readers hold %d pieces; %d pages of %d pieces fit", held, fit, pieces) |
| 1295 | } |
| 1296 | if grew := int64(after.HeapAlloc) - int64(before.HeapAlloc); grew > MaxBuffered+8<<20 { |
| 1297 | t.Errorf("%d slow readers of %d bytes each grew the heap by %d bytes, past MaxBuffered", n, size, grew) |
| 1298 | } |
| 1299 | |
| 1300 | client := &http.Client{Timeout: 10 * time.Second} |
| 1301 | get := func(target string) (int, string) { |
| 1302 | t.Helper() |
| 1303 | resp, err := client.Get("http://" + ln.Addr().String() + target) |
| 1304 | if err != nil { |
| 1305 | t.Fatal(err) |
| 1306 | } |
| 1307 | defer resp.Body.Close() |
| 1308 | io.Copy(io.Discard, resp.Body) |
| 1309 | return resp.StatusCode, resp.Header.Get("Retry-After") |
| 1310 | } |
| 1311 | if code, retry := get(target); code != http.StatusServiceUnavailable || retry == "" { |
| 1312 | t.Errorf("a page the budget has no room for answered %d, Retry-After %q", code, retry) |
| 1313 | } |
| 1314 | if code, _ := get("/knots/app/oc-a000002"); code != http.StatusOK { |
| 1315 | t.Errorf("a small page answered %d while slow readers hold most of the budget", code) |
| 1316 | } |
| 1317 | |
| 1318 | close(sl.release) |
| 1319 | released = true |
| 1320 | codes := map[int]int{} |
| 1321 | for _, c := range conns { |
| 1322 | c.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| 1323 | resp, err := http.ReadResponse(bufio.NewReader(c), nil) |
| 1324 | if err != nil { |
| 1325 | t.Fatal(err) |
| 1326 | } |
| 1327 | read, err := io.Copy(io.Discard, resp.Body) |
| 1328 | resp.Body.Close() |
| 1329 | if err != nil || resp.StatusCode == http.StatusOK && read != int64(size) { |
| 1330 | t.Errorf("a slow reader read %d bytes of %d: %v", read, size, err) |
| 1331 | } |
| 1332 | codes[resp.StatusCode]++ |
| 1333 | } |
| 1334 | if codes[http.StatusOK] != fit || codes[http.StatusServiceUnavailable] != n-fit { |
| 1335 | t.Errorf("of %d slow readers, %d were served and %d answered 503; %d pages fit the budget", |
| 1336 | n, codes[http.StatusOK], codes[http.StatusServiceUnavailable], fit) |
| 1337 | } |
| 1338 | eventually(t, "the budget is whole again", func() bool { return len(h.srv.budget) == 0 }) |
| 1339 | } |
| 1340 | |
| 1341 | // A load starts only once a request that waits for it takes a loader |
| 1342 | // slot. While MaxLoads loads run, a request for a newer generation waits |
| 1343 | // for a slot, holding no generation, until its time runs out, whatever |
| 1344 | // its route, or its reader goes away. Neither leaves a load behind. |
| 1345 | func TestExportLoadWaitsEnd(t *testing.T) { |
| 1346 | h := newHarness(t) |
| 1347 | var mu sync.Mutex |
| 1348 | var logged []string |
| 1349 | h.srv.log = func(err error) { |
| 1350 | mu.Lock() |
| 1351 | defer mu.Unlock() |
| 1352 | logged = append(logged, err.Error()) |
| 1353 | } |
| 1354 | loads := map[int64]int{} |
| 1355 | hold := make(chan struct{}) |
| 1356 | h.srv.loading = func(g export.Generation) { |
| 1357 | mu.Lock() |
| 1358 | loads[g.Sequence]++ |
| 1359 | mu.Unlock() |
| 1360 | <-hold |
| 1361 | } |
| 1362 | loaded := func(g export.Generation) int { |
| 1363 | mu.Lock() |
| 1364 | defer mu.Unlock() |
| 1365 | return loads[g.Sequence] |
| 1366 | } |
| 1367 | serve := func(r *http.Request) chan *httptest.ResponseRecorder { |
| 1368 | served := make(chan *httptest.ResponseRecorder, 1) |
| 1369 | go func() { |
| 1370 | w := httptest.NewRecorder() |
| 1371 | h.srv.ServeHTTP(w, r) |
| 1372 | served <- w |
| 1373 | }() |
| 1374 | return served |
| 1375 | } |
| 1376 | expect := func(served chan *httptest.ResponseRecorder, title string) { |
| 1377 | t.Helper() |
| 1378 | select { |
| 1379 | case w := <-served: |
| 1380 | if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) { |
| 1381 | t.Errorf("a request answered %d, not with %q", w.Code, title) |
| 1382 | } |
| 1383 | case <-time.After(10 * time.Second): |
| 1384 | t.Fatalf("a request was not answered with %q", title) |
| 1385 | } |
| 1386 | } |
| 1387 | |
| 1388 | first := h.active() |
| 1389 | firstServed := serve(httptest.NewRequest("GET", "/", nil)) |
| 1390 | eventually(t, "the first generation is read", func() bool { return loaded(first) == 1 }) |
| 1391 | second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 1392 | secondServed := serve(httptest.NewRequest("GET", "/", nil)) |
| 1393 | eventually(t, "both loader slots are taken", func() bool { return loaded(second) == 1 }) |
| 1394 | |
| 1395 | // A request that runs no git runs out of time waiting, and answers |
| 1396 | // 503. |
| 1397 | h.srv.timeout = 200 * time.Millisecond |
| 1398 | third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan")) |
| 1399 | select { |
| 1400 | case w := <-serve(httptest.NewRequest("GET", "/knots/app/oc-a000001", nil)): |
| 1401 | if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 1402 | t.Errorf("a request that waited past its time for a read answered %d", w.Code) |
| 1403 | } |
| 1404 | case <-time.After(10 * time.Second): |
| 1405 | t.Fatal("a request waits for a read past its time of 200ms") |
| 1406 | } |
| 1407 | |
| 1408 | // A request whose reader goes away stops waiting, and answers |
| 1409 | // nothing. |
| 1410 | h.srv.timeout = time.Hour |
| 1411 | fourth := h.publish(exporttest.SignedAt.Add(3*time.Minute), nil, renamed("Readers browse the fourth plan")) |
| 1412 | ctx, cancel := context.WithCancel(context.Background()) |
| 1413 | defer cancel() |
| 1414 | gone := serve(httptest.NewRequest("GET", "/", nil).WithContext(ctx)) |
| 1415 | eventually(t, "a request waits for the fourth generation", func() bool { return len(h.srv.loadWaiting) == 3 }) |
| 1416 | cancel() |
| 1417 | select { |
| 1418 | case w := <-gone: |
| 1419 | if w.Body.Len() != 0 { |
| 1420 | t.Errorf("a request whose reader went away answered %d", w.Code) |
| 1421 | } |
| 1422 | case <-time.After(10 * time.Second): |
| 1423 | t.Fatal("a request whose reader went away still waits") |
| 1424 | } |
| 1425 | |
| 1426 | h.srv.mu.Lock() |
| 1427 | left := len(h.srv.loads) |
| 1428 | h.srv.mu.Unlock() |
| 1429 | if left != MaxLoads { |
| 1430 | t.Errorf("%d loads may be joined; only the %d that run are wanted", left, MaxLoads) |
| 1431 | } |
| 1432 | h.publish(exporttest.SignedAt.Add(4*time.Minute), nil, renamed("Readers browse the fifth plan")) |
| 1433 | for _, g := range []export.Generation{third, fourth} { |
| 1434 | if _, err := os.Stat(g.Dir); !os.IsNotExist(err) { |
| 1435 | t.Errorf("generation %d outlived an activation after its request gave up: %v", g.Sequence, err) |
| 1436 | } |
| 1437 | } |
| 1438 | |
| 1439 | // The first two reads end, and their requests are served the newest |
| 1440 | // generation. |
| 1441 | close(hold) |
| 1442 | expect(firstServed, "Readers browse the fifth plan") |
| 1443 | expect(secondServed, "Readers browse the fifth plan") |
| 1444 | for _, g := range []export.Generation{third, fourth} { |
| 1445 | if n := loaded(g); n != 0 { |
| 1446 | t.Errorf("generation %d's export was read %d times after every request for it gave up", g.Sequence, n) |
| 1447 | } |
| 1448 | } |
| 1449 | mu.Lock() |
| 1450 | defer mu.Unlock() |
| 1451 | if len(logged) != 1 || !strings.Contains(logged[0], "deadline exceeded") { |
| 1452 | t.Errorf("the server logged %q; it logs the one request that ran out of time", logged) |
| 1453 | } |
| 1454 | } |
| 1455 | |
| 1456 | // A load that reads slowly does not hold the request that waits for it: |
| 1457 | // the request answers 503 at its deadline. With no request left waiting, |
| 1458 | // the load stops reading part way through the export, caches nothing, and |
| 1459 | // gives back its generation, which the next activation deletes. A load |
| 1460 | // that ends is kept, and the requests after it are served without another |
| 1461 | // read. |
| 1462 | func TestSlowLoadEndsWithItsRequests(t *testing.T) { |
| 1463 | h := newHarness(t) |
| 1464 | h.srv.timeout = 200 * time.Millisecond |
| 1465 | var mu sync.Mutex |
| 1466 | var logged []string |
| 1467 | h.srv.log = func(err error) { |
| 1468 | mu.Lock() |
| 1469 | defer mu.Unlock() |
| 1470 | logged = append(logged, err.Error()) |
| 1471 | } |
| 1472 | var reads atomic.Int32 |
| 1473 | h.srv.loading = func(export.Generation) { reads.Add(1) } |
| 1474 | |
| 1475 | // The active generation's export.json becomes a pipe the test writes |
| 1476 | // a few bytes at a time, as a slow disk would give it: all of it |
| 1477 | // takes about 4 seconds, twenty times the request's time. |
| 1478 | old := h.active() |
| 1479 | data, err := os.ReadFile(old.ExportPath()) |
| 1480 | if err != nil { |
| 1481 | t.Fatal(err) |
| 1482 | } |
| 1483 | if err := os.Remove(old.ExportPath()); err != nil { |
| 1484 | t.Fatal(err) |
| 1485 | } |
| 1486 | if err := syscall.Mkfifo(old.ExportPath(), 0o600); err != nil { |
| 1487 | t.Fatal(err) |
| 1488 | } |
| 1489 | piece := max(1, len(data)/200) |
| 1490 | wrote := make(chan error, 1) |
| 1491 | go func() { |
| 1492 | f, err := os.OpenFile(old.ExportPath(), os.O_WRONLY, 0) |
| 1493 | if err != nil { |
| 1494 | wrote <- err |
| 1495 | return |
| 1496 | } |
| 1497 | defer f.Close() |
| 1498 | for p := data; len(p) > 0; p = p[min(len(p), piece):] { |
| 1499 | if _, err := f.Write(p[:min(len(p), piece)]); err != nil { |
| 1500 | wrote <- err |
| 1501 | return |
| 1502 | } |
| 1503 | time.Sleep(20 * time.Millisecond) |
| 1504 | } |
| 1505 | wrote <- nil |
| 1506 | }() |
| 1507 | |
| 1508 | start := time.Now() |
| 1509 | if w := h.get("/"); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 1510 | t.Errorf("a request whose load ran past its time answered %d", w.Code) |
| 1511 | } |
| 1512 | if waited := time.Since(start); waited > 2*time.Second { |
| 1513 | t.Errorf("a request waited %v for a slow load, past its time of 200ms", waited) |
| 1514 | } |
| 1515 | select { |
| 1516 | case err := <-wrote: |
| 1517 | if !errors.Is(err, syscall.EPIPE) { |
| 1518 | t.Errorf("the load read the whole export after its request gave up: the writer ended with %v", err) |
| 1519 | } |
| 1520 | case <-time.After(10 * time.Second): |
| 1521 | t.Fatal("the load still reads the export") |
| 1522 | } |
| 1523 | eventually(t, "the load ends", func() bool { return len(h.srv.loaders) == 0 }) |
| 1524 | h.srv.mu.Lock() |
| 1525 | cached, loads := h.srv.cached, len(h.srv.loads) |
| 1526 | h.srv.mu.Unlock() |
| 1527 | if cached != nil || loads != 0 { |
| 1528 | t.Errorf("a load that stopped left a snapshot %v and %d loads", cached != nil, loads) |
| 1529 | } |
| 1530 | // The store reads the active export.json when it takes an upload. |
| 1531 | if err := os.Remove(old.ExportPath()); err != nil { |
| 1532 | t.Fatal(err) |
| 1533 | } |
| 1534 | if err := os.WriteFile(old.ExportPath(), data, 0o644); err != nil { |
| 1535 | t.Fatal(err) |
| 1536 | } |
| 1537 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 1538 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 1539 | t.Errorf("the generation a stopped load opened outlived an activation: %v", err) |
| 1540 | } |
| 1541 | |
| 1542 | h.srv.timeout = requestTimeout |
| 1543 | for range 3 { |
| 1544 | if !strings.Contains(h.page("/knots/app/oc-a000001"), "Readers browse the second plan") { |
| 1545 | t.Error("a request after the stopped load is not served the new generation") |
| 1546 | } |
| 1547 | } |
| 1548 | if n := reads.Load(); n != 2 { |
| 1549 | t.Errorf("exports were read %d times: once in part, and once for the new generation", n) |
| 1550 | } |
| 1551 | mu.Lock() |
| 1552 | defer mu.Unlock() |
| 1553 | if len(logged) != 1 || !strings.Contains(logged[0], "export to be read: context deadline exceeded") { |
| 1554 | t.Errorf("the server logged %q; it logs the one request that ran out of time", logged) |
| 1555 | } |
| 1556 | } |
| 1557 | |
| 1558 | // openFiles is the number of files the process holds open, and false |
| 1559 | // where the system does not list them. |
| 1560 | func openFiles(t *testing.T) (int, bool) { |
| 1561 | t.Helper() |
| 1562 | entries, err := os.ReadDir("/proc/self/fd") |
| 1563 | if err != nil { |
| 1564 | return 0, false |
| 1565 | } |
| 1566 | return len(entries), true |
| 1567 | } |
| 1568 | |
| 1569 | // A flood of requests while a load runs: MaxLoadWaiting of them wait, and |
| 1570 | // the rest answer 503 at once, unlogged. A waiting request holds no |
| 1571 | // generation, so the goroutines and files the server holds stay within a |
| 1572 | // bound however large the flood. Once the load ends, every request that |
| 1573 | // waited is served from its one read. |
| 1574 | func TestLoadFlood(t *testing.T) { |
| 1575 | h := newHarness(t) |
| 1576 | var reads atomic.Int32 |
| 1577 | reading, hold := make(chan struct{}, 1), make(chan struct{}) |
| 1578 | h.srv.loading = func(export.Generation) { |
| 1579 | reads.Add(1) |
| 1580 | reading <- struct{}{} |
| 1581 | <-hold |
| 1582 | } |
| 1583 | get := func(n int) chan *httptest.ResponseRecorder { |
| 1584 | served := make(chan *httptest.ResponseRecorder, n) |
| 1585 | for range n { |
| 1586 | go func() { |
| 1587 | w := httptest.NewRecorder() |
| 1588 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil)) |
| 1589 | served <- w |
| 1590 | }() |
| 1591 | } |
| 1592 | return served |
| 1593 | } |
| 1594 | |
| 1595 | first := get(1) |
| 1596 | select { |
| 1597 | case <-reading: |
| 1598 | case <-time.After(10 * time.Second): |
| 1599 | t.Fatal("no load started") |
| 1600 | } |
| 1601 | goroutines := runtime.NumGoroutine() |
| 1602 | files, listed := openFiles(t) |
| 1603 | |
| 1604 | flood := 4 * MaxLoadWaiting |
| 1605 | served := get(flood) |
| 1606 | refused := flood - (MaxLoadWaiting - 1) |
| 1607 | for range refused { |
| 1608 | if w := <-served; w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 1609 | t.Fatalf("a request past MaxLoadWaiting answered %d", w.Code) |
| 1610 | } |
| 1611 | } |
| 1612 | if n := len(h.srv.loadWaiting); n != MaxLoadWaiting { |
| 1613 | t.Errorf("%d requests wait for the load, not %d", n, MaxLoadWaiting) |
| 1614 | } |
| 1615 | const slack = 8 |
| 1616 | eventually(t, "the refused requests' goroutines end", func() bool { |
| 1617 | return runtime.NumGoroutine() <= goroutines+MaxLoadWaiting-1+slack |
| 1618 | }) |
| 1619 | if n, _ := openFiles(t); listed && n > files+slack { |
| 1620 | t.Errorf("the flood holds %d files open, %d more than before it", n, n-files) |
| 1621 | } |
| 1622 | |
| 1623 | close(hold) |
| 1624 | for range MaxLoadWaiting - 1 { |
| 1625 | if w := <-served; w.Code != http.StatusOK { |
| 1626 | t.Errorf("a request that waited for the load answered %d", w.Code) |
| 1627 | } |
| 1628 | } |
| 1629 | if w := <-first; w.Code != http.StatusOK { |
| 1630 | t.Errorf("the request that started the load answered %d", w.Code) |
| 1631 | } |
| 1632 | if n := reads.Load(); n != 1 { |
| 1633 | t.Errorf("the export was read %d times for one generation", n) |
| 1634 | } |
| 1635 | if n := len(h.srv.loadWaiting); n != 0 { |
| 1636 | t.Errorf("%d requests still hold a place among those that wait", n) |
| 1637 | } |
| 1638 | } |
| 1639 | |
| 1640 | // A request's time runs from its arrival through its rendering: a request |
| 1641 | // for a page that runs no git, held past its time before it renders, |
| 1642 | // answers 503, and the server logs it. |
| 1643 | func TestRenderingIsWithinTheDeadline(t *testing.T) { |
| 1644 | h := newHarness(t) |
| 1645 | h.page("/") |
| 1646 | h.srv.timeout = 50 * time.Millisecond |
| 1647 | var logged []string |
| 1648 | h.srv.log = func(err error) { logged = append(logged, err.Error()) } |
| 1649 | h.srv.opened = func(export.Generation) { time.Sleep(100 * time.Millisecond) } |
| 1650 | if w := h.get("/"); w.Code != http.StatusServiceUnavailable || !bytes.Equal(w.Body.Bytes(), busyPage) { |
| 1651 | t.Errorf("a request that ran out of time before it rendered answered %d", w.Code) |
| 1652 | } |
| 1653 | if len(logged) != 1 || !strings.Contains(logged[0], "rendering plan: context deadline exceeded") { |
| 1654 | t.Errorf("the server logged %q", logged) |
| 1655 | } |
| 1656 | if n := len(h.srv.budget); n != 0 { |
| 1657 | t.Errorf("a page that stopped rendering kept %d pieces of the budget", n) |
| 1658 | } |
| 1659 | } |