| 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, by project, in place of the |
| 85 | // fixture's. |
| 86 | func (h *harness) publish(at time.Time, bundles map[string]string, change func(*export.Export)) export.Generation { |
| 87 | t := h.t |
| 88 | t.Helper() |
| 89 | e, err := export.Decode(h.f.ExportJSON) |
| 90 | if err != nil { |
| 91 | t.Fatal(err) |
| 92 | } |
| 93 | change(e) |
| 94 | data, err := e.Encode() |
| 95 | if err != nil { |
| 96 | t.Fatal(err) |
| 97 | } |
| 98 | paths := map[string]string{} |
| 99 | for _, p := range e.Projects { |
| 100 | if paths[p.Name] = bundles[p.Name]; paths[p.Name] == "" { |
| 101 | paths[p.Name] = h.f.Bundles[p.Name] |
| 102 | } |
| 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="/app/knots/bd-a000004">`) { |
| 234 | t.Error("bd-a000004 is not shown as free to start") |
| 235 | } |
| 236 | |
| 237 | // The milestone's path puts oc-a000003 after the knot it waits on. |
| 238 | paths := section(t, page, `id="paths-h"`, `id="ms-h"`) |
| 239 | second := strings.Index(paths, `<span class="stage-num">2</span>`) |
| 240 | if second < 0 || strings.Index(paths, "oc-a000002") > second || strings.Index(paths, "oc-a000003") < second { |
| 241 | t.Errorf("the path does not order oc-a000003 after oc-a000002:\n%s", paths) |
| 242 | } |
| 243 | |
| 244 | // Nothing of the hidden project is linked or named, and nothing is |
| 245 | // fetched from another origin. |
| 246 | for _, want := range []string{"lands in an unpublished project", "lands in a knot in an unpublished project"} { |
| 247 | if !strings.Contains(page, want) { |
| 248 | t.Errorf("the plan page does not show %q", want) |
| 249 | } |
| 250 | } |
| 251 | for _, unwanted := range append([]string{"/site/knots/", "/site/source/", "http://", "https://", `class="chip stale"`}, unpublishedText...) { |
| 252 | if strings.Contains(page, unwanted) { |
| 253 | t.Errorf("the plan page holds %q", unwanted) |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | h.now = exporttest.Collected.Add(6 * time.Minute) |
| 258 | page = h.page("/") |
| 259 | if !strings.Contains(page, `Collected 2026-10-25 12:00 UTC, 6 minutes ago <span class="chip stale">stale</span>`) { |
| 260 | t.Error("an export six minutes old is not marked stale") |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | // 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("/app/knots/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="/app/knots/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("/app/knots/oc-a000003") |
| 291 | if !strings.Contains(page, `<a href="/app/knots/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("/app/knots/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{"/site/knots/", "/site/source/"}, unpublishedText...) { |
| 307 | if strings.Contains(page, unwanted) { |
| 308 | t.Errorf("the knot's page shows %q", unwanted) |
| 309 | } |
| 310 | } |
| 311 | if w := h.get("/app/knots/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("/app/knots/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("/app/knots/oc-fffffff") |
| 356 | for _, route := range []string{ |
| 357 | "/%s", |
| 358 | "/%s/", |
| 359 | "/%s/knots/oc-b000001", |
| 360 | "/%s/source", |
| 361 | "/%s/source/", |
| 362 | "/%s/source/tree/" + siteTip + "/", |
| 363 | "/%s/source/blob/" + siteTip + "/README.md", |
| 364 | "/%s/source/log/" + siteTip, |
| 365 | "/%s/source/tree/" + siteTip + "/no/such/path/", |
| 366 | "/%s/source/anything", |
| 367 | } { |
| 368 | hidden, missing := h.get(fmt.Sprintf(route, "site")), h.get(fmt.Sprintf(route, "nosuch")) |
| 369 | if hidden.Code != http.StatusNotFound || missing.Code != http.StatusNotFound { |
| 370 | t.Errorf("%s answered %d hidden and %d missing", route, hidden.Code, missing.Code) |
| 371 | } |
| 372 | if fmt.Sprint(hidden.Header()) != fmt.Sprint(missing.Header()) { |
| 373 | t.Errorf("%s answered with other headers hidden than missing:\n%v\n%v", route, hidden.Header(), missing.Header()) |
| 374 | } |
| 375 | if !bytes.Equal(hidden.Body.Bytes(), missing.Body.Bytes()) || !bytes.Equal(hidden.Body.Bytes(), notFound.Body.Bytes()) { |
| 376 | t.Errorf("%s answered with another page hidden than missing", route) |
| 377 | } |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | // A project's name may be any word the server's routes use: source, |
| 382 | // knots, or web-export, the receiver's first segment. Each such project |
| 383 | // is served on every route, and /<project>/ redirects to its tree. The |
| 384 | // server's own paths, under /-/, are never a project's. |
| 385 | func TestProjectNamesBesideTheServersPaths(t *testing.T) { |
| 386 | for _, name := range []string{"source", "knots", "web-export"} { |
| 387 | t.Run(name, func(t *testing.T) { |
| 388 | h := newHarness(t) |
| 389 | h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{name: h.f.Bundles["app"]}, |
| 390 | func(e *export.Export) { e.Projects[0].Name = name }) |
| 391 | tip := h.tip() |
| 392 | tree := "/" + name + "/source/tree/" + tip + "/" |
| 393 | if plan := h.page("/"); !strings.Contains(plan, `href="/`+name+`/knots/oc-a000002"`) { |
| 394 | t.Errorf("the plan page does not link %s's knots", name) |
| 395 | } |
| 396 | for _, target := range []string{ |
| 397 | "/" + name + "/knots/oc-a000002", |
| 398 | tree, |
| 399 | "/" + name + "/source/blob/" + tip + "/docs/guide.md", |
| 400 | "/" + name + "/source/log/" + tip, |
| 401 | } { |
| 402 | h.page(target) |
| 403 | } |
| 404 | for _, target := range []string{"/" + name + "/", "/" + name, "/" + name + "/source/"} { |
| 405 | if w := h.get(target); w.Code != http.StatusFound || w.Header().Get("Location") != tree { |
| 406 | t.Errorf("GET %s answered %d to %q, not a redirect to %s", target, w.Code, w.Header().Get("Location"), tree) |
| 407 | } |
| 408 | } |
| 409 | for _, target := range []string{ |
| 410 | "/-", "/-/", "/-/" + name + "/", "/-/knots/oc-a000002", "/-/source/tree/" + tip + "/", |
| 411 | "/-/" + name + "/source/tree/" + tip + "/", "/app/", "/site/", "/site", |
| 412 | } { |
| 413 | if w := h.get(target); w.Code != http.StatusNotFound { |
| 414 | t.Errorf("GET %s answered %d, not 404", target, w.Code) |
| 415 | } |
| 416 | } |
| 417 | }) |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | // A source route serves a commit only when main's published tip reaches |
| 422 | // it, and refuses every other object ID or name with the one 404. |
| 423 | func TestUnreachableCommitIsRefused(t *testing.T) { |
| 424 | h := newHarness(t) |
| 425 | repo, _ := h.active().Repo("app") |
| 426 | tip := h.tip() |
| 427 | tree := git(t, repo, nil, "rev-parse", tip+"^{tree}") |
| 428 | readme := git(t, repo, nil, "rev-parse", tip+":README.md") |
| 429 | side := git(t, repo, nil, "commit-tree", tree, "-p", tip, "-m", "a commit main does not reach") |
| 430 | parent := git(t, repo, nil, "rev-parse", tip+"~2") |
| 431 | notFound := h.get("/app/knots/oc-fffffff").Body.String() |
| 432 | |
| 433 | for _, commit := range []string{side, tree, readme, tip[:12], "main", "HEAD", strings.Repeat("0", 40), tip + "~1"} { |
| 434 | for _, route := range []string{"/app/source/tree/%s/", "/app/source/blob/%s/README.md", "/app/source/log/%s"} { |
| 435 | target := fmt.Sprintf(route, commit) |
| 436 | w := h.get(target) |
| 437 | if w.Code != http.StatusNotFound || w.Body.String() != notFound { |
| 438 | t.Errorf("GET %s answered %d, not the one 404", target, w.Code) |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | // A commit the tip reaches is served, as that commit had it. |
| 444 | page := h.page("/app/source/blob/" + parent + "/README.md") |
| 445 | if !strings.Contains(page, "A synthetic project for the web UI's tests.") || strings.Contains(page, "readme") { |
| 446 | t.Errorf("the first README is not served as the first commit had it:\n%s", page) |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | // The source browser lists a directory and its README, shows a file and |
| 451 | // main's log, and every source link names its project, a full commit and |
| 452 | // a path. |
| 453 | func TestSourceBrowser(t *testing.T) { |
| 454 | h := newHarness(t) |
| 455 | tip := h.tip() |
| 456 | |
| 457 | for _, path := range []string{"/app/source", "/app/source/"} { |
| 458 | w := h.get(path) |
| 459 | if w.Code != http.StatusFound || w.Header().Get("Location") != "/app/source/tree/"+tip+"/" { |
| 460 | t.Fatalf("the project's source answered %d to %q", w.Code, w.Header().Get("Location")) |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | root := h.page("/app/source/tree/" + tip + "/") |
| 465 | docs, src, readme := strings.Index(root, ">docs/<"), strings.Index(root, ">src/<"), strings.Index(root, ">README.md<") |
| 466 | if docs < 0 || src < 0 || readme < 0 || readme < src || src < docs { |
| 467 | t.Errorf("the root does not list docs/ and src/ before README.md:\n%s", root) |
| 468 | } |
| 469 | if !strings.Contains(root, `<pre class="text"># app`) { |
| 470 | t.Error("the root does not show its README") |
| 471 | } |
| 472 | if dir := h.page("/app/source/tree/" + tip + "/docs/"); !strings.Contains(dir, ">guide.md<") { |
| 473 | t.Error("docs/ does not list guide.md") |
| 474 | } |
| 475 | file := h.page("/app/source/blob/" + tip + "/docs/guide.md") |
| 476 | if !strings.Contains(file, `<tr id="L1"><td class="ln"><a href="#L1">1</a></td><td class="src"># Guide</td></tr>`) { |
| 477 | t.Errorf("the file is not shown line by line:\n%s", file) |
| 478 | } |
| 479 | log := h.page("/app/source/log/" + tip) |
| 480 | first, last := strings.Index(log, "docs: a guide, and the README names it"), strings.Index(log, "app: the first README") |
| 481 | if first < 0 || last < first { |
| 482 | t.Errorf("the log does not list main's commits newest first:\n%s", log) |
| 483 | } |
| 484 | |
| 485 | links := regexp.MustCompile(`href="(/[^"]*/source/[^"]*)"`) |
| 486 | named := regexp.MustCompile(`^/app/source/(tree|blob|log)/[0-9a-f]{40}(/|$)`) |
| 487 | for _, page := range []string{root, file, log} { |
| 488 | for _, m := range links.FindAllStringSubmatch(page, -1) { |
| 489 | if !named.MatchString(m[1]) { |
| 490 | t.Errorf("the link %s names no commit", m[1]) |
| 491 | } |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | for _, target := range []string{ |
| 496 | "/app/source/tree/" + tip + "/README.md/", |
| 497 | "/app/source/blob/" + tip + "/docs", |
| 498 | "/app/source/blob/" + tip + "/docs/guide.md/", |
| 499 | "/app/source/blob/" + tip + "/docs/../README.md", |
| 500 | "/app/source/blob/" + tip + "/docs%2Fguide.md", |
| 501 | "/app/source/tree/" + tip + "//", |
| 502 | "/app/source/log/" + tip + "?skip=-1", |
| 503 | } { |
| 504 | if w := h.get(target); w.Code != http.StatusNotFound { |
| 505 | t.Errorf("GET %s answered %d", target, w.Code) |
| 506 | } |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | // file is one file a test commits: its mode, path and content. |
| 511 | type file struct{ mode, path, content string } |
| 512 | |
| 513 | // commitMain writes a commit onto the fixture's app main, with message, |
| 514 | // that holds the files given beside what main holds. It returns the new |
| 515 | // tip and a bundle of it. Each content is written once, however many |
| 516 | // files hold it. |
| 517 | func (h *harness) commitMain(message string, files ...file) (tip, bundle string) { |
| 518 | t := h.t |
| 519 | t.Helper() |
| 520 | repo := h.f.Repos["app"] |
| 521 | var b bytes.Buffer |
| 522 | data := func(s string) { fmt.Fprintf(&b, "data %d\n%s\n", len(s), s) } |
| 523 | marks := map[string]int{} |
| 524 | for _, f := range files { |
| 525 | if _, ok := marks[f.content]; !ok { |
| 526 | marks[f.content] = len(marks) + 1 |
| 527 | fmt.Fprintf(&b, "blob\nmark :%d\n", marks[f.content]) |
| 528 | data(f.content) |
| 529 | } |
| 530 | } |
| 531 | who := "Example Author <author@example.org> 1791190800 +0000" |
| 532 | fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who) |
| 533 | data(message) |
| 534 | fmt.Fprintf(&b, "from %s\n", git(t, repo, nil, "rev-parse", export.MainRef)) |
| 535 | for _, f := range files { |
| 536 | fmt.Fprintf(&b, "M %s :%d %s\n", f.mode, marks[f.content], f.path) |
| 537 | } |
| 538 | git(t, repo, b.Bytes(), "fast-import", "--quiet") |
| 539 | tip = git(t, repo, nil, "rev-parse", export.MainRef) |
| 540 | bundle = filepath.Join(t.TempDir(), "app.bundle") |
| 541 | git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main") |
| 542 | return tip, bundle |
| 543 | } |
| 544 | |
| 545 | // publishMain activates a generation whose app main is tip, carried by |
| 546 | // bundle. |
| 547 | func (h *harness) publishMain(at time.Time, tip, bundle string) { |
| 548 | h.t.Helper() |
| 549 | h.publish(at, map[string]string{"app": bundle}, func(e *export.Export) { e.Projects[0].SourceTip = tip }) |
| 550 | } |
| 551 | |
| 552 | // hostileMain writes a commit onto the fixture's app main that holds a |
| 553 | // file of HTML, a file larger than a page shows, a binary file, a file |
| 554 | // whose name is HTML, and a symbolic link out of the repository. It |
| 555 | // returns the new tip and a bundle of it. |
| 556 | func (h *harness) hostileMain() (tip, bundle string) { |
| 557 | return h.commitMain("hostile: <script>alert(\"subject\")</script>\n", |
| 558 | file{"100644", "page.html", "<html><script>alert(\"file\")</script><img src=x onerror=alert(2)></html>\n"}, |
| 559 | file{"100644", "big.txt", strings.Repeat("big\n", (MaxFile/4)+1)}, |
| 560 | file{"100644", "binary.bin", "\x7fELF\x00\x01\x02<script>alert(\"binary\")</script>"}, |
| 561 | file{"100644", "<img src=x onerror=alert(3)>.txt", "named\n"}, |
| 562 | file{"120000", "link", "../../etc/passwd"}, |
| 563 | ) |
| 564 | } |
| 565 | |
| 566 | // HTML, scripts, large files and binary files from a repository or the |
| 567 | // plan render inert: escaped as text, or not shown. |
| 568 | func TestHostileContentRendersInert(t *testing.T) { |
| 569 | h := newHarness(t) |
| 570 | tip, bundle := h.hostileMain() |
| 571 | h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) { |
| 572 | e.Projects[0].SourceTip = tip |
| 573 | }) |
| 574 | |
| 575 | inert := func(target, page string, wants ...string) { |
| 576 | t.Helper() |
| 577 | // Escaped, a tag is text; only a tag the page did not escape, or |
| 578 | // an attribute it let a value break out into, is active. |
| 579 | for _, active := range []string{"<script", "<img", `" onerror`, "\x00"} { |
| 580 | if strings.Contains(page, active) { |
| 581 | t.Errorf("GET %s holds %q", target, active) |
| 582 | } |
| 583 | } |
| 584 | for _, want := range wants { |
| 585 | if !strings.Contains(page, want) { |
| 586 | t.Errorf("GET %s does not show %q", target, want) |
| 587 | } |
| 588 | } |
| 589 | } |
| 590 | at := "/app/source/tree/" + tip + "/" |
| 591 | inert(at, h.page(at), |
| 592 | `<script>alert("readme")</script>`, |
| 593 | `<img src=x onerror=alert(3)>.txt`, |
| 594 | `href="/app/source/blob/`+tip+`/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"`) |
| 595 | at = "/app/source/blob/" + tip + "/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt" |
| 596 | inert(at, h.page(at), ">named<") |
| 597 | at = "/app/source/blob/" + tip + "/page.html" |
| 598 | inert(at, h.page(at), `<html><script>alert("file")</script><img src=x onerror=alert(2)></html>`) |
| 599 | at = "/app/source/blob/" + tip + "/big.txt" |
| 600 | page := h.page(at) |
| 601 | inert(at, page, "This file is 1.0 MiB, larger than the 1.0 MiB a page shows.") |
| 602 | if len(page) > 64<<10 { |
| 603 | t.Errorf("the large file's page is %d bytes", len(page)) |
| 604 | } |
| 605 | at = "/app/source/blob/" + tip + "/binary.bin" |
| 606 | inert(at, h.page(at), "This file is binary, 39 bytes, and is not shown.") |
| 607 | at = "/app/source/blob/" + tip + "/link" |
| 608 | inert(at, h.page(at), "A symbolic link to ../../etc/passwd. It is not followed.") |
| 609 | at = "/app/source/log/" + tip |
| 610 | inert(at, h.page(at), "hostile: <script>alert("subject")</script>") |
| 611 | |
| 612 | at = "/app/knots/bd-a000004" |
| 613 | inert(at, h.page(at), |
| 614 | `A README holding <script>alert("knot")</script> must show as text.`, |
| 615 | `Also <img src=x onerror=alert(1)> in a comment.`) |
| 616 | } |
| 617 | |
| 618 | // A directory larger than a page reads is listed in part, and a commit |
| 619 | // message larger than a page reads ends its page of history early. git |
| 620 | // is stopped once its listing passes MaxRead, and nothing past a record's |
| 621 | // bound is kept. |
| 622 | func TestOversizedTreeAndHistory(t *testing.T) { |
| 623 | h := newHarness(t) |
| 624 | // Each entry of huge/ takes 308 bytes of git ls-tree's output, so |
| 625 | // 15,000 of them pass MaxRead at about entry 13,600. |
| 626 | longest := "!" + strings.Repeat("l", 4095) |
| 627 | files := []file{{"100644", "huge/" + longest, "x\n"}} |
| 628 | name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) } |
| 629 | for i := range 15_000 { |
| 630 | files = append(files, file{"100644", "huge/" + name(i), "x\n"}) |
| 631 | } |
| 632 | if n := 15_000 * (6 + 1 + 4 + 1 + 40 + 1 + 7 + 1 + 246 + 1); n <= MaxRead { |
| 633 | t.Fatalf("the listing of huge/ is %d bytes, within MaxRead", n) |
| 634 | } |
| 635 | h.commitMain("app: a directory larger than a page reads\n", files...) |
| 636 | h.commitMain("long: " + strings.Repeat("a long subject ", (100<<10)/15) + "\n") |
| 637 | tip, bundle := h.commitMain("longer: " + strings.Repeat("a subject past the bound ", (5<<20)/25) + "\n") |
| 638 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 639 | |
| 640 | at := "/app/source/tree/" + tip + "/huge/" |
| 641 | page := h.page(at) |
| 642 | if !strings.Contains(page, "This directory is larger than a page reads, so only part of it is listed.") { |
| 643 | t.Error("huge/ is not marked as listed in part") |
| 644 | } |
| 645 | if n := strings.Count(page, `<tr><td class="name">`); n != MaxEntries { |
| 646 | t.Errorf("huge/ lists %d entries, not %d", n, MaxEntries) |
| 647 | } |
| 648 | if !strings.Contains(page, `">`+longest+`</a>`) { |
| 649 | t.Error("the entry with the longest name git accepts is not listed whole") |
| 650 | } |
| 651 | if len(page) > 1<<20 { |
| 652 | t.Errorf("huge/'s page is %d bytes", len(page)) |
| 653 | } |
| 654 | if w := h.get("/app/source/blob/" + tip + "/huge/" + name(0)); w.Code != http.StatusOK { |
| 655 | t.Errorf("an entry read before MaxRead answered %d", w.Code) |
| 656 | } |
| 657 | if w := h.get("/app/source/blob/" + tip + "/huge/" + name(14_999)); w.Code != http.StatusNotFound { |
| 658 | t.Errorf("an entry past MaxRead answered %d", w.Code) |
| 659 | } |
| 660 | |
| 661 | at = "/app/source/log/" + tip |
| 662 | page = h.page(at) |
| 663 | if !strings.Contains(page, "This page ends early: its commits are larger than a page reads.") { |
| 664 | t.Error("the page of history holding a 5 MiB message does not end early") |
| 665 | } |
| 666 | if n := strings.Count(page, `<tr><td class="name">`); n != 1 { |
| 667 | t.Errorf("the page that ends early lists %d commits, not the one it cut", n) |
| 668 | } |
| 669 | if m := regexp.MustCompile(`<td>(longer: a subject past the bound[^<]*)…</td>`).FindStringSubmatch(page); m == nil || len(m[1]) > maxLogText { |
| 670 | t.Error("the cut commit's subject is not shown cut to maxLogText") |
| 671 | } |
| 672 | if !strings.Contains(page, `href="/app/source/log/`+tip+`?skip=1"`) { |
| 673 | t.Error("the page that ends early does not link the commits after the one it cut") |
| 674 | } |
| 675 | page = h.page(at + "?skip=1") |
| 676 | if strings.Contains(page, "ends early") || !strings.Contains(page, "long: a long subject") || !strings.Contains(page, "app: the first README") { |
| 677 | t.Errorf("the next page of history is not whole:\n%s", page) |
| 678 | } |
| 679 | if strings.Contains(page, strings.Repeat("a long subject ", (maxLogText/15)+1)) { |
| 680 | t.Error("a subject longer than a page shows is not cut") |
| 681 | } |
| 682 | for _, p := range []string{at, at + "?skip=1"} { |
| 683 | if n := len(h.page(p)); n > 64<<10 { |
| 684 | t.Errorf("GET %s is %d bytes", p, n) |
| 685 | } |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | // A file of exactly MaxFile bytes of newlines is shown to MaxLines lines, |
| 690 | // and its page says where it stops. A README longer than a page shows is |
| 691 | // shown in part. |
| 692 | func TestLongFileIsShownInPart(t *testing.T) { |
| 693 | h := newHarness(t) |
| 694 | tip, bundle := h.commitMain("app: long files\n", |
| 695 | file{"100644", "newlines.txt", strings.Repeat("\n", MaxFile)}, |
| 696 | file{"100644", "long/README.md", strings.Repeat("a line of the README\n", 2*MaxLines)}, |
| 697 | file{"100644", "wide.txt", strings.Repeat("<", MaxFile)}, |
| 698 | ) |
| 699 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 700 | |
| 701 | page := h.page("/app/source/blob/" + tip + "/newlines.txt") |
| 702 | last := fmt.Sprintf(`id="L%d"`, MaxLines) |
| 703 | if !strings.Contains(page, last) || strings.Contains(page, fmt.Sprintf(`id="L%d"`, MaxLines+1)) { |
| 704 | t.Errorf("the file of newlines is not shown to line %d", MaxLines) |
| 705 | } |
| 706 | if want := fmt.Sprintf("The page stops at line %d of %d.", MaxLines, MaxFile); !strings.Contains(page, want) { |
| 707 | t.Errorf("the page does not say %q", want) |
| 708 | } |
| 709 | if len(page) > MaxShown { |
| 710 | t.Errorf("the page of a file of newlines is %d bytes, past MaxShown", len(page)) |
| 711 | } |
| 712 | |
| 713 | // One line of MaxFile characters that each escape to four bytes is |
| 714 | // cut where MaxShown is reached. |
| 715 | page = h.page("/app/source/blob/" + tip + "/wide.txt") |
| 716 | if !strings.Contains(page, "The page stops at line 1 of 1.") || len(page) > MaxShown+64<<10 { |
| 717 | t.Errorf("the page of one wide line is %d bytes", len(page)) |
| 718 | } |
| 719 | |
| 720 | page = h.page("/app/source/tree/" + tip + "/long/") |
| 721 | if !strings.Contains(page, "This README is longer than a page shows, and only its start is shown.") { |
| 722 | t.Error("the long README is not marked as shown in part") |
| 723 | } |
| 724 | if n := strings.Count(page, "a line of the README"); n != MaxLines { |
| 725 | t.Errorf("the long README shows %d lines, not %d", n, MaxLines) |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | // A chain of knots as deep as the graph's knot limit allows renders its |
| 730 | // milestone to MaxPlanDepth levels, counts every knot under it, and |
| 731 | // names MaxPlanDepth parents in the deepest knot's trail. The plan page's |
| 732 | // structure is built once for the generation. Siblings that block one |
| 733 | // another in a cycle share the last stage of their path. |
| 734 | func TestDeepPlan(t *testing.T) { |
| 735 | h := newHarness(t) |
| 736 | var chain []string |
| 737 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) { |
| 738 | p := &e.Projects[0] |
| 739 | for i := range knot.MaxKnots - len(p.Knots) - 3 { |
| 740 | id := fmt.Sprintf("oc-c%06x", i) |
| 741 | k := export.Knot{ID: id, Type: "outcome", Status: "open", Active: true, State: "ready", |
| 742 | Title: fmt.Sprintf("Level %d of the chain", i), Created: "2026-10-01", CreatedBy: "operator"} |
| 743 | if i == 0 { |
| 744 | p.Roots = append(p.Roots, id) |
| 745 | } else { |
| 746 | k.Parent = chain[i-1] |
| 747 | p.Knots[len(p.Knots)-1].Children = []string{id} |
| 748 | } |
| 749 | chain = append(chain, id) |
| 750 | p.Knots = append(p.Knots, k) |
| 751 | } |
| 752 | // Under the first link, a path whose two last siblings wait on |
| 753 | // each other. |
| 754 | free, a, b := "oc-d000001", "oc-d000002", "oc-d000003" |
| 755 | for _, k := range []export.Knot{ |
| 756 | {ID: free, BlockedBy: []string{}}, |
| 757 | {ID: a, BlockedBy: []string{free, b}}, |
| 758 | {ID: b, BlockedBy: []string{a}}, |
| 759 | } { |
| 760 | k.Type, k.Status, k.State, k.Title, k.Parent = "outcome", "open", "blocked", "Sibling "+k.ID, chain[0] |
| 761 | p.Knots = append(p.Knots, k) |
| 762 | } |
| 763 | for i := range p.Knots { |
| 764 | if p.Knots[i].ID == chain[0] { |
| 765 | p.Knots[i].Children = append(p.Knots[i].Children, free, a, b) |
| 766 | } |
| 767 | } |
| 768 | }) |
| 769 | |
| 770 | page := h.page("/") |
| 771 | if want := fmt.Sprintf("%d of %d done", 0, len(chain)-1+3); !strings.Contains(page, want) { |
| 772 | t.Errorf("the chain's milestone does not count every knot under it as %q", want) |
| 773 | } |
| 774 | if !strings.Contains(page, `href="/app/knots/`+chain[MaxPlanDepth]+`"`) || strings.Contains(page, `href="/app/knots/`+chain[MaxPlanDepth+1]+`"`) { |
| 775 | t.Errorf("the chain's tree is not shown to %d levels", MaxPlanDepth) |
| 776 | } |
| 777 | if n := strings.Count(page, ">more on its page<"); n != 1 { |
| 778 | t.Errorf("%d rows say there is more on their page; the chain's deepest shown row does", n) |
| 779 | } |
| 780 | if len(page) > 256<<10 { |
| 781 | t.Errorf("the plan page is %d bytes", len(page)) |
| 782 | } |
| 783 | paths := section(t, page, `id="paths-h"`, `id="ms-h"`) |
| 784 | stage := regexp.MustCompile(`<span class="stage-num">(\d+)</span><ul class="plain">(.*?)</ul>`) |
| 785 | var stages []string |
| 786 | for _, m := range stage.FindAllStringSubmatch(paths, -1) { |
| 787 | if strings.Contains(m[2], "Sibling") { |
| 788 | var ids []string |
| 789 | for _, id := range regexp.MustCompile(`"mono muted">(oc-d00000\d)<`).FindAllStringSubmatch(m[2], -1) { |
| 790 | ids = append(ids, id[1]) |
| 791 | } |
| 792 | stages = append(stages, m[1]+":"+strings.Join(ids, ",")) |
| 793 | } |
| 794 | } |
| 795 | if got := strings.Join(stages, " "); got != "1:oc-d000001 2:oc-d000002,oc-d000003" { |
| 796 | t.Errorf("the siblings' path has stages %q", got) |
| 797 | } |
| 798 | |
| 799 | h.srv.mu.Lock() |
| 800 | plan := h.srv.cached.idx.plan |
| 801 | h.srv.mu.Unlock() |
| 802 | h.page("/") |
| 803 | h.srv.mu.Lock() |
| 804 | again := h.srv.cached.idx.plan |
| 805 | h.srv.mu.Unlock() |
| 806 | if plan != again { |
| 807 | t.Error("the plan page's structure was built again for the same generation") |
| 808 | } |
| 809 | |
| 810 | deepest := chain[len(chain)-1] |
| 811 | page = h.page("/app/knots/" + deepest) |
| 812 | trail := section(t, page, `<nav class="trail"`, `</nav>`) |
| 813 | if n := strings.Count(trail, `<a href="/app/knots/`); n != MaxPlanDepth || !strings.Contains(trail, "<span>…</span>") { |
| 814 | t.Errorf("the deepest knot's trail names %d parents, or does not mark those above them", n) |
| 815 | } |
| 816 | if !strings.Contains(trail, chain[len(chain)-2]) || strings.Contains(trail, `"/app/knots/`+chain[len(chain)-2-MaxPlanDepth]+`"`) { |
| 817 | t.Error("the trail does not name the nearest parents alone") |
| 818 | } |
| 819 | } |
| 820 | |
| 821 | // Every response carries the strict policy, and the policy admits the |
| 822 | // page's one inline stylesheet and one inline script by their hashes and |
| 823 | // nothing from another origin. |
| 824 | func TestEveryResponseCarriesTheCSP(t *testing.T) { |
| 825 | h := newHarness(t) |
| 826 | for _, c := range []struct{ method, target string }{ |
| 827 | {"GET", "/"}, |
| 828 | {"GET", "/app/knots/oc-a000002"}, |
| 829 | {"GET", "/app/source/"}, |
| 830 | {"GET", "/app/source/tree/" + h.tip() + "/"}, |
| 831 | {"GET", "/app/source/blob/" + h.tip() + "/README.md"}, |
| 832 | {"GET", "/no/such/page"}, |
| 833 | {"POST", "/"}, |
| 834 | {"HEAD", "/"}, |
| 835 | } { |
| 836 | w := h.do(c.method, c.target) |
| 837 | got := w.Header().Get("Content-Security-Policy") |
| 838 | if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" { |
| 839 | t.Errorf("%s %s answered with policy %q", c.method, c.target, got) |
| 840 | } |
| 841 | } |
| 842 | for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} { |
| 843 | if !strings.Contains(csp, directive) { |
| 844 | t.Errorf("the policy lacks %s", directive) |
| 845 | } |
| 846 | } |
| 847 | for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} { |
| 848 | if strings.Contains(csp, loose) { |
| 849 | t.Errorf("the policy holds %q", loose) |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | page := h.page("/") |
| 854 | inline := func(tag string) string { |
| 855 | t.Helper() |
| 856 | m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1) |
| 857 | if len(m) != 1 || strings.Count(page, "<"+tag) != 1 { |
| 858 | t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag) |
| 859 | } |
| 860 | sum := sha256.Sum256([]byte(m[0][1])) |
| 861 | return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'" |
| 862 | } |
| 863 | if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") { |
| 864 | t.Errorf("the policy does not admit the page's script, %s", hash) |
| 865 | } |
| 866 | if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") { |
| 867 | t.Errorf("the policy does not admit the page's stylesheet, %s", hash) |
| 868 | } |
| 869 | for _, external := range []string{"<link", " src=", "@import", "url("} { |
| 870 | if strings.Contains(page, external) { |
| 871 | t.Errorf("the plan page holds %q", external) |
| 872 | } |
| 873 | } |
| 874 | } |
| 875 | |
| 876 | // A request serves everything from the generation it opened, though |
| 877 | // another activates while it runs, and that generation outlives the |
| 878 | // activation until the request releases it. |
| 879 | func TestARequestKeepsItsGeneration(t *testing.T) { |
| 880 | h := newHarness(t) |
| 881 | paused, resume := make(chan export.Generation), make(chan struct{}) |
| 882 | var once sync.Once |
| 883 | h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) } |
| 884 | served := make(chan *httptest.ResponseRecorder) |
| 885 | go func() { |
| 886 | w := httptest.NewRecorder() |
| 887 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/knots/oc-a000001", nil)) |
| 888 | served <- w |
| 889 | }() |
| 890 | old := <-paused |
| 891 | |
| 892 | next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 893 | if next.Sequence == old.Sequence { |
| 894 | t.Fatal("the publish did not activate a new generation") |
| 895 | } |
| 896 | if _, err := os.Stat(old.Dir); err != nil { |
| 897 | t.Fatalf("the generation a request holds was deleted: %v", err) |
| 898 | } |
| 899 | close(resume) |
| 900 | w := <-served |
| 901 | if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app's plan") || strings.Contains(body, "second plan") { |
| 902 | t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body) |
| 903 | } |
| 904 | if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the second plan") { |
| 905 | t.Error("the next request does not serve the new generation") |
| 906 | } |
| 907 | |
| 908 | // Released, the old generation goes with the next activation. |
| 909 | h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan")) |
| 910 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 911 | t.Errorf("the released generation is still on disk: %v", err) |
| 912 | } |
| 913 | } |
| 914 | |
| 915 | // eventually waits up to ten seconds for cond to hold. |
| 916 | func eventually(t *testing.T, what string, cond func() bool) { |
| 917 | t.Helper() |
| 918 | for deadline := time.Now().Add(10 * time.Second); !cond(); time.Sleep(time.Millisecond) { |
| 919 | if time.Now().After(deadline) { |
| 920 | t.Fatalf("timed out waiting until %s", what) |
| 921 | } |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | // renamed changes the title of the fixture's first knot. |
| 926 | func renamed(title string) func(*export.Export) { |
| 927 | return func(e *export.Export) { e.Projects[0].Knots[0].Title = title } |
| 928 | } |
| 929 | |
| 930 | // Requests that wait for a generation together read its export once. |
| 931 | // While it is read, a newer generation is read on its own, and at most |
| 932 | // MaxLoads exports are read at once. A request whose load ends after a |
| 933 | // newer generation was activated waits for that one, so every request is |
| 934 | // served the generation active when its snapshot is ready, and an older |
| 935 | // read that finishes last does not displace the newest snapshot. |
| 936 | func TestExportLoadsCoalesce(t *testing.T) { |
| 937 | h := newHarness(t) |
| 938 | var mu sync.Mutex |
| 939 | loads := map[int64]int{} |
| 940 | holds := map[int64]chan struct{}{} |
| 941 | hold := func(g export.Generation) chan struct{} { |
| 942 | mu.Lock() |
| 943 | defer mu.Unlock() |
| 944 | if holds[g.Sequence] == nil { |
| 945 | holds[g.Sequence] = make(chan struct{}) |
| 946 | } |
| 947 | return holds[g.Sequence] |
| 948 | } |
| 949 | h.srv.loading = func(g export.Generation) { |
| 950 | mu.Lock() |
| 951 | loads[g.Sequence]++ |
| 952 | mu.Unlock() |
| 953 | <-hold(g) |
| 954 | } |
| 955 | loaded := func(g export.Generation) int { |
| 956 | mu.Lock() |
| 957 | defer mu.Unlock() |
| 958 | return loads[g.Sequence] |
| 959 | } |
| 960 | var opens atomic.Int32 |
| 961 | h.srv.opened = func(export.Generation) { opens.Add(1) } |
| 962 | get := func(n int) chan *httptest.ResponseRecorder { |
| 963 | served := make(chan *httptest.ResponseRecorder, n) |
| 964 | for range n { |
| 965 | go func() { |
| 966 | w := httptest.NewRecorder() |
| 967 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/app/knots/oc-a000001", nil)) |
| 968 | served <- w |
| 969 | }() |
| 970 | } |
| 971 | return served |
| 972 | } |
| 973 | expect := func(served chan *httptest.ResponseRecorder, n int, title string) { |
| 974 | t.Helper() |
| 975 | for range n { |
| 976 | if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) { |
| 977 | t.Errorf("a request answered %d, not with %q", w.Code, title) |
| 978 | } |
| 979 | } |
| 980 | } |
| 981 | waiting := func(n int) func() bool { return func() bool { return len(h.srv.loadWaiting) == n } } |
| 982 | |
| 983 | first := h.active() |
| 984 | firstServed := get(10) |
| 985 | eventually(t, "ten requests wait for the first generation's read", func() bool { |
| 986 | return loaded(first) == 1 && len(h.srv.loadWaiting) == 10 |
| 987 | }) |
| 988 | second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 989 | secondServed := get(1) |
| 990 | eventually(t, "the second generation is read", func() bool { return loaded(second) == 1 }) |
| 991 | |
| 992 | // Both loaders are taken, so the third generation waits for one. |
| 993 | third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan")) |
| 994 | thirdServed := get(1) |
| 995 | eventually(t, "a request waits for the third generation", waiting(12)) |
| 996 | time.Sleep(20 * time.Millisecond) |
| 997 | if n := loaded(third); n != 0 { |
| 998 | t.Errorf("a third export was read while %d were", MaxLoads) |
| 999 | } |
| 1000 | if n := opens.Load(); n != 0 { |
| 1001 | t.Errorf("%d requests opened a generation while they waited for its read", n) |
| 1002 | } |
| 1003 | |
| 1004 | // The second read ends, and its request finds the third generation |
| 1005 | // active, and waits for that read with the third's request. |
| 1006 | close(hold(second)) |
| 1007 | eventually(t, "the third generation is read", func() bool { return loaded(third) == 1 }) |
| 1008 | close(hold(third)) |
| 1009 | expect(secondServed, 1, "Readers browse the third plan") |
| 1010 | expect(thirdServed, 1, "Readers browse the third plan") |
| 1011 | close(hold(first)) |
| 1012 | expect(firstServed, 10, "Readers browse the third plan") |
| 1013 | |
| 1014 | if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the third plan") { |
| 1015 | t.Error("the first generation's read displaced the third's") |
| 1016 | } |
| 1017 | for _, g := range []export.Generation{first, second, third} { |
| 1018 | if n := loaded(g); n != 1 { |
| 1019 | t.Errorf("generation %d's export was read %d times", g.Sequence, n) |
| 1020 | } |
| 1021 | } |
| 1022 | } |
| 1023 | |
| 1024 | // Source requests past MaxGit wait, MaxWaiting of them, and one more |
| 1025 | // answers 503 at once. A waiting request holds no generation, so an |
| 1026 | // activation while the server is saturated deletes the old generation, |
| 1027 | // and every waiting request serves the new one. A request's time runs |
| 1028 | // from its arrival, so one that waits past it answers 503. |
| 1029 | func TestSourceAdmission(t *testing.T) { |
| 1030 | h := newHarness(t) |
| 1031 | var admitted atomic.Int32 |
| 1032 | release := make(chan struct{}) |
| 1033 | h.srv.admitted = func() { |
| 1034 | admitted.Add(1) |
| 1035 | <-release |
| 1036 | } |
| 1037 | target := "/app/source/tree/" + h.tip() + "/" |
| 1038 | get := func(n int) chan *httptest.ResponseRecorder { |
| 1039 | served := make(chan *httptest.ResponseRecorder, n) |
| 1040 | for range n { |
| 1041 | go func() { |
| 1042 | w := httptest.NewRecorder() |
| 1043 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", target, nil)) |
| 1044 | served <- w |
| 1045 | }() |
| 1046 | } |
| 1047 | return served |
| 1048 | } |
| 1049 | |
| 1050 | old := h.active() |
| 1051 | served := get(MaxGit + MaxWaiting) |
| 1052 | eventually(t, "every slot is taken and MaxWaiting requests wait", func() bool { |
| 1053 | return admitted.Load() == MaxGit && len(h.srv.waiting) == MaxWaiting |
| 1054 | }) |
| 1055 | if w := h.get(target); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 1056 | t.Errorf("a source request past MaxWaiting answered %d, Retry-After %q", w.Code, w.Header().Get("Retry-After")) |
| 1057 | } |
| 1058 | h.page("/") // a page that runs no git is served still |
| 1059 | |
| 1060 | tip, bundle := h.commitMain("app: a commit while the server is saturated\n", file{"100644", "saturated.txt", "saturated\n"}) |
| 1061 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1062 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 1063 | t.Errorf("a generation no request had opened outlived the activation: %v", err) |
| 1064 | } |
| 1065 | close(release) |
| 1066 | for range MaxGit + MaxWaiting { |
| 1067 | if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "/app/source/tree/"+tip+"/") { |
| 1068 | t.Errorf("a waiting request answered %d, not from the new generation", w.Code) |
| 1069 | } |
| 1070 | } |
| 1071 | |
| 1072 | // A request that waits past its time answers 503. Those that held |
| 1073 | // the slots meanwhile ran out of time too. |
| 1074 | h.srv.timeout = 200 * time.Millisecond |
| 1075 | h.srv.log = func(error) {} |
| 1076 | admitted.Store(0) |
| 1077 | release = make(chan struct{}) |
| 1078 | held := get(MaxGit) |
| 1079 | eventually(t, "every slot is taken", func() bool { return admitted.Load() == MaxGit }) |
| 1080 | start := time.Now() |
| 1081 | if w := h.get(target); w.Code != http.StatusServiceUnavailable { |
| 1082 | t.Errorf("a request that waited past its time answered %d", w.Code) |
| 1083 | } |
| 1084 | if waited := time.Since(start); waited > 5*time.Second { |
| 1085 | t.Errorf("a request waited %v past its time of 200ms", waited) |
| 1086 | } |
| 1087 | close(release) |
| 1088 | for range MaxGit { |
| 1089 | if w := <-held; w.Code != http.StatusServiceUnavailable { |
| 1090 | t.Errorf("a request that ran out of time answered %d", w.Code) |
| 1091 | } |
| 1092 | } |
| 1093 | } |
| 1094 | |
| 1095 | // stallingListener accepts connections whose writes stall until release |
| 1096 | // is closed, while stall is set. Each sends on stalled the first time one |
| 1097 | // of its writes stalls. |
| 1098 | type stallingListener struct { |
| 1099 | net.Listener |
| 1100 | stall atomic.Bool |
| 1101 | release chan struct{} |
| 1102 | stalled chan struct{} |
| 1103 | } |
| 1104 | |
| 1105 | func (l *stallingListener) Accept() (net.Conn, error) { |
| 1106 | c, err := l.Listener.Accept() |
| 1107 | if err != nil || !l.stall.Load() { |
| 1108 | return c, err |
| 1109 | } |
| 1110 | return &stallingConn{Conn: c, l: l}, nil |
| 1111 | } |
| 1112 | |
| 1113 | type stallingConn struct { |
| 1114 | net.Conn |
| 1115 | l *stallingListener |
| 1116 | once sync.Once |
| 1117 | } |
| 1118 | |
| 1119 | func (c *stallingConn) Write(p []byte) (int, error) { |
| 1120 | c.once.Do(func() { c.l.stalled <- struct{}{} }) |
| 1121 | <-c.l.release |
| 1122 | return c.Conn.Write(p) |
| 1123 | } |
| 1124 | |
| 1125 | // Readers that never read their responses hold no git slot and no |
| 1126 | // generation: more of them than MaxGit and MaxWaiting together are |
| 1127 | // stalled writing, and a new reader is still served, and an activation |
| 1128 | // deletes the generation they were served from. |
| 1129 | func TestSlowReadersHoldNothing(t *testing.T) { |
| 1130 | h := newHarness(t) |
| 1131 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 1132 | if err != nil { |
| 1133 | t.Fatal(err) |
| 1134 | } |
| 1135 | n := MaxGit + MaxWaiting + 4 |
| 1136 | sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)} |
| 1137 | sl.stall.Store(true) |
| 1138 | srv := &http.Server{Handler: h.srv} |
| 1139 | go srv.Serve(sl) |
| 1140 | var conns []net.Conn |
| 1141 | defer func() { |
| 1142 | close(sl.release) |
| 1143 | for _, c := range conns { |
| 1144 | c.Close() |
| 1145 | } |
| 1146 | srv.Close() |
| 1147 | }() |
| 1148 | |
| 1149 | old := h.active() |
| 1150 | target := "/app/source/blob/" + h.tip() + "/docs/guide.md" |
| 1151 | for range n { |
| 1152 | c, err := net.Dial("tcp", ln.Addr().String()) |
| 1153 | if err != nil { |
| 1154 | t.Fatal(err) |
| 1155 | } |
| 1156 | conns = append(conns, c) |
| 1157 | fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target) |
| 1158 | } |
| 1159 | for i := range n { |
| 1160 | select { |
| 1161 | case <-sl.stalled: |
| 1162 | case <-time.After(10 * time.Second): |
| 1163 | t.Fatalf("%d of %d slow readers' responses were written; the rest wait", i, n) |
| 1164 | } |
| 1165 | } |
| 1166 | sl.stall.Store(false) |
| 1167 | if len(h.srv.slots) != 0 || len(h.srv.waiting) != 0 { |
| 1168 | t.Errorf("slow readers hold %d git slots, and %d requests wait", len(h.srv.slots), len(h.srv.waiting)) |
| 1169 | } |
| 1170 | |
| 1171 | client := &http.Client{Timeout: 10 * time.Second} |
| 1172 | resp, err := client.Get("http://" + ln.Addr().String() + target) |
| 1173 | if err != nil { |
| 1174 | t.Fatal(err) |
| 1175 | } |
| 1176 | resp.Body.Close() |
| 1177 | if resp.StatusCode != http.StatusOK { |
| 1178 | t.Errorf("a new reader answered %d while slow readers stall", resp.StatusCode) |
| 1179 | } |
| 1180 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(*export.Export) {}) |
| 1181 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 1182 | t.Errorf("the generation slow readers were served from outlived the activation: %v", err) |
| 1183 | } |
| 1184 | } |
| 1185 | |
| 1186 | // Before the first activation the server says nothing is published, and |
| 1187 | // it answers GET and HEAD alone. |
| 1188 | func TestNothingPublishedAndMethods(t *testing.T) { |
| 1189 | store, err := export.OpenStore(t.TempDir(), nil) |
| 1190 | if err != nil { |
| 1191 | t.Fatal(err) |
| 1192 | } |
| 1193 | srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }}) |
| 1194 | w := httptest.NewRecorder() |
| 1195 | srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil)) |
| 1196 | if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") { |
| 1197 | t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body) |
| 1198 | } |
| 1199 | |
| 1200 | h := newHarness(t) |
| 1201 | for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} { |
| 1202 | w := h.do(method, "/") |
| 1203 | if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" { |
| 1204 | t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow")) |
| 1205 | } |
| 1206 | } |
| 1207 | } |
| 1208 | |
| 1209 | // tooLarge checks that GET target answers with the one short page that |
| 1210 | // says a page is too large. |
| 1211 | func (h *harness) tooLarge(target string) { |
| 1212 | h.t.Helper() |
| 1213 | w := h.get(target) |
| 1214 | if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) { |
| 1215 | 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()) |
| 1216 | } |
| 1217 | if n := len(h.srv.budget); n != 0 { |
| 1218 | h.t.Errorf("GET %s kept %d pieces of the budget", target, n) |
| 1219 | } |
| 1220 | } |
| 1221 | |
| 1222 | // A response's body is at most MaxResponse bytes. A page that would pass |
| 1223 | // the bound answers with the one short page that says it is too large, |
| 1224 | // and the failure is logged: a knot whose body passes MaxResponse, and, |
| 1225 | // under a smaller bound, a file, a directory, a page of history and the |
| 1226 | // plan page. A page within the bound is served on each route. |
| 1227 | func TestPageTooLarge(t *testing.T) { |
| 1228 | h := newHarness(t) |
| 1229 | var logged []string |
| 1230 | h.srv.log = func(err error) { logged = append(logged, err.Error()) } |
| 1231 | files := []file{{"100644", "wide.txt", strings.Repeat("<", 16<<10)}} |
| 1232 | for i := range 32 { |
| 1233 | files = append(files, file{"100644", fmt.Sprintf("wide/%02d-%s", i, strings.Repeat("n", 1000)), "x\n"}) |
| 1234 | } |
| 1235 | h.commitMain("app: a wide file and a wide directory\n", files...) |
| 1236 | var tip, bundle string |
| 1237 | for i := range 8 { |
| 1238 | tip, bundle = h.commitMain(fmt.Sprintf("%d %s\n", i, strings.Repeat(`"`, maxLogText))) |
| 1239 | } |
| 1240 | h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) { |
| 1241 | p := &e.Projects[0] |
| 1242 | p.SourceTip = tip |
| 1243 | p.Knots[0].Body = strings.Repeat("a", MaxResponse) |
| 1244 | for i := range 100 { |
| 1245 | p.Knots = append(p.Knots, export.Knot{ID: fmt.Sprintf("oc-e%06x", i), Type: "outcome", Status: "open", |
| 1246 | Active: true, State: "ready", Title: strings.Repeat(`"`, knot.MaxTitle), Created: "2026-10-01", CreatedBy: "operator"}) |
| 1247 | } |
| 1248 | }) |
| 1249 | |
| 1250 | h.tooLarge("/app/knots/" + h.f.Export.Projects[0].Knots[0].ID) |
| 1251 | h.page("/app/knots/oc-a000002") |
| 1252 | |
| 1253 | h.srv.maxResponse = 32 << 10 |
| 1254 | at := "/app/source/blob/" + tip + "/" |
| 1255 | h.tooLarge(at + "wide.txt") |
| 1256 | h.page(at + "docs/guide.md") |
| 1257 | at = "/app/source/tree/" + tip + "/" |
| 1258 | h.tooLarge(at + "wide/") |
| 1259 | h.page(at + "docs/") |
| 1260 | h.tooLarge("/app/source/log/" + tip) |
| 1261 | h.page("/app/source/log/" + tip + "?skip=8") |
| 1262 | h.tooLarge("/") |
| 1263 | |
| 1264 | if len(logged) != 5 { |
| 1265 | t.Errorf("%d failures were logged for 5 pages too large: %q", len(logged), logged) |
| 1266 | } |
| 1267 | for _, l := range logged { |
| 1268 | if !strings.Contains(l, "larger than") { |
| 1269 | t.Errorf("the server logged %q", l) |
| 1270 | } |
| 1271 | } |
| 1272 | if len(tooLargePage) > 16<<10 { |
| 1273 | t.Errorf("the page that says a page is too large is %d bytes", len(tooLargePage)) |
| 1274 | } |
| 1275 | } |
| 1276 | |
| 1277 | // Rendered responses share a budget of MaxBuffered bytes, which each |
| 1278 | // holds from when it starts rendering until it is written. What a |
| 1279 | // response renders past its first SmallPage bytes takes only MaxLarge of |
| 1280 | // it. Readers that never read large pages ask for twice the budget in |
| 1281 | // all, with pages sized so that, but for MaxLarge, sixteen of them would |
| 1282 | // hold all of it. Once their pages hold MaxLarge, a large page answers |
| 1283 | // 503 at once, while small pages still render: the plan, a knot and a |
| 1284 | // directory. The server's heap grows by no more than the budget, and the |
| 1285 | // budget is whole again once the readers read. |
| 1286 | func TestSlowReadersShareTheBudget(t *testing.T) { |
| 1287 | h := newHarness(t) |
| 1288 | target := "/app/knots/" + h.f.Export.Projects[0].Knots[0].ID |
| 1289 | body := func(at time.Duration, text string) { |
| 1290 | h.publish(exporttest.SignedAt.Add(at), nil, func(e *export.Export) { e.Projects[0].Knots[0].Body = text }) |
| 1291 | } |
| 1292 | body(time.Minute, "x") |
| 1293 | rest := len(h.page(target)) - 1 |
| 1294 | pieces := 64 |
| 1295 | body(2*time.Minute, strings.Repeat("a line of a long body\n", (pieces*pieceSize-rest-1024)/22)) |
| 1296 | size := len(h.page(target)) |
| 1297 | if got := (size + pieceSize - 1) / pieceSize; got != pieces || cap(h.srv.budget)%pieces != 0 { |
| 1298 | t.Fatalf("the large page takes %d pieces, not %d, which divide the budget", got, pieces) |
| 1299 | } |
| 1300 | fit := cap(h.srv.large) / (pieces - smallPieces) |
| 1301 | n := 2*MaxBuffered/size + 1 |
| 1302 | |
| 1303 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 1304 | if err != nil { |
| 1305 | t.Fatal(err) |
| 1306 | } |
| 1307 | sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)} |
| 1308 | sl.stall.Store(true) |
| 1309 | srv := &http.Server{Handler: h.srv} |
| 1310 | go srv.Serve(sl) |
| 1311 | var conns []net.Conn |
| 1312 | released := false |
| 1313 | defer func() { |
| 1314 | if !released { |
| 1315 | close(sl.release) |
| 1316 | } |
| 1317 | for _, c := range conns { |
| 1318 | c.Close() |
| 1319 | } |
| 1320 | srv.Close() |
| 1321 | }() |
| 1322 | |
| 1323 | var before runtime.MemStats |
| 1324 | runtime.GC() |
| 1325 | runtime.ReadMemStats(&before) |
| 1326 | // One reader at a time, each stalled before the next asks, so the |
| 1327 | // readers that fill the budget are the first fit of them. |
| 1328 | for i := range n { |
| 1329 | c, err := net.Dial("tcp", ln.Addr().String()) |
| 1330 | if err != nil { |
| 1331 | t.Fatal(err) |
| 1332 | } |
| 1333 | conns = append(conns, c) |
| 1334 | fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target) |
| 1335 | select { |
| 1336 | case <-sl.stalled: |
| 1337 | case <-time.After(10 * time.Second): |
| 1338 | t.Fatalf("reader %d of %d was not answered", i+1, n) |
| 1339 | } |
| 1340 | } |
| 1341 | sl.stall.Store(false) |
| 1342 | var after runtime.MemStats |
| 1343 | runtime.GC() |
| 1344 | runtime.ReadMemStats(&after) |
| 1345 | if held, large := len(h.srv.budget), len(h.srv.large); held != fit*pieces || large != fit*(pieces-smallPieces) { |
| 1346 | t.Errorf("slow readers hold %d pieces, %d of them large; %d pages of %d pieces fit", held, large, fit, pieces) |
| 1347 | } |
| 1348 | if grew := int64(after.HeapAlloc) - int64(before.HeapAlloc); grew > MaxBuffered+8<<20 { |
| 1349 | t.Errorf("%d slow readers of %d bytes each grew the heap by %d bytes, past MaxBuffered", n, size, grew) |
| 1350 | } |
| 1351 | |
| 1352 | client := &http.Client{Timeout: 10 * time.Second} |
| 1353 | get := func(target string) (int, string) { |
| 1354 | t.Helper() |
| 1355 | resp, err := client.Get("http://" + ln.Addr().String() + target) |
| 1356 | if err != nil { |
| 1357 | t.Fatal(err) |
| 1358 | } |
| 1359 | defer resp.Body.Close() |
| 1360 | io.Copy(io.Discard, resp.Body) |
| 1361 | return resp.StatusCode, resp.Header.Get("Retry-After") |
| 1362 | } |
| 1363 | if code, retry := get(target); code != http.StatusServiceUnavailable || retry == "" { |
| 1364 | t.Errorf("a page the budget has no room for answered %d, Retry-After %q", code, retry) |
| 1365 | } |
| 1366 | for _, small := range []string{"/", "/app/knots/oc-a000002", "/app/source/tree/" + h.tip() + "/"} { |
| 1367 | if code, _ := get(small); code != http.StatusOK { |
| 1368 | t.Errorf("the small page %s answered %d while slow readers hold MaxLarge", small, code) |
| 1369 | } |
| 1370 | } |
| 1371 | |
| 1372 | close(sl.release) |
| 1373 | released = true |
| 1374 | codes := map[int]int{} |
| 1375 | for _, c := range conns { |
| 1376 | c.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| 1377 | resp, err := http.ReadResponse(bufio.NewReader(c), nil) |
| 1378 | if err != nil { |
| 1379 | t.Fatal(err) |
| 1380 | } |
| 1381 | read, err := io.Copy(io.Discard, resp.Body) |
| 1382 | resp.Body.Close() |
| 1383 | if err != nil || resp.StatusCode == http.StatusOK && read != int64(size) { |
| 1384 | t.Errorf("a slow reader read %d bytes of %d: %v", read, size, err) |
| 1385 | } |
| 1386 | codes[resp.StatusCode]++ |
| 1387 | } |
| 1388 | if codes[http.StatusOK] != fit || codes[http.StatusServiceUnavailable] != n-fit { |
| 1389 | t.Errorf("of %d slow readers, %d were served and %d answered 503; %d pages fit the budget", |
| 1390 | n, codes[http.StatusOK], codes[http.StatusServiceUnavailable], fit) |
| 1391 | } |
| 1392 | eventually(t, "the budget is whole again", func() bool { return len(h.srv.budget) == 0 }) |
| 1393 | } |
| 1394 | |
| 1395 | // A load starts only once a request that waits for it takes a loader |
| 1396 | // slot. While MaxLoads loads run, a request for a newer generation waits |
| 1397 | // for a slot, holding no generation, until its time runs out, whatever |
| 1398 | // its route, or its reader goes away. Neither leaves a load behind. |
| 1399 | func TestExportLoadWaitsEnd(t *testing.T) { |
| 1400 | h := newHarness(t) |
| 1401 | var mu sync.Mutex |
| 1402 | var logged []string |
| 1403 | h.srv.log = func(err error) { |
| 1404 | mu.Lock() |
| 1405 | defer mu.Unlock() |
| 1406 | logged = append(logged, err.Error()) |
| 1407 | } |
| 1408 | loads := map[int64]int{} |
| 1409 | hold := make(chan struct{}) |
| 1410 | h.srv.loading = func(g export.Generation) { |
| 1411 | mu.Lock() |
| 1412 | loads[g.Sequence]++ |
| 1413 | mu.Unlock() |
| 1414 | <-hold |
| 1415 | } |
| 1416 | loaded := func(g export.Generation) int { |
| 1417 | mu.Lock() |
| 1418 | defer mu.Unlock() |
| 1419 | return loads[g.Sequence] |
| 1420 | } |
| 1421 | serve := func(r *http.Request) chan *httptest.ResponseRecorder { |
| 1422 | served := make(chan *httptest.ResponseRecorder, 1) |
| 1423 | go func() { |
| 1424 | w := httptest.NewRecorder() |
| 1425 | h.srv.ServeHTTP(w, r) |
| 1426 | served <- w |
| 1427 | }() |
| 1428 | return served |
| 1429 | } |
| 1430 | expect := func(served chan *httptest.ResponseRecorder, title string) { |
| 1431 | t.Helper() |
| 1432 | select { |
| 1433 | case w := <-served: |
| 1434 | if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) { |
| 1435 | t.Errorf("a request answered %d, not with %q", w.Code, title) |
| 1436 | } |
| 1437 | case <-time.After(10 * time.Second): |
| 1438 | t.Fatalf("a request was not answered with %q", title) |
| 1439 | } |
| 1440 | } |
| 1441 | |
| 1442 | first := h.active() |
| 1443 | firstServed := serve(httptest.NewRequest("GET", "/", nil)) |
| 1444 | eventually(t, "the first generation is read", func() bool { return loaded(first) == 1 }) |
| 1445 | second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 1446 | secondServed := serve(httptest.NewRequest("GET", "/", nil)) |
| 1447 | eventually(t, "both loader slots are taken", func() bool { return loaded(second) == 1 }) |
| 1448 | |
| 1449 | // A request that runs no git runs out of time waiting, and answers |
| 1450 | // 503. |
| 1451 | h.srv.timeout = 200 * time.Millisecond |
| 1452 | third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan")) |
| 1453 | select { |
| 1454 | case w := <-serve(httptest.NewRequest("GET", "/app/knots/oc-a000001", nil)): |
| 1455 | if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 1456 | t.Errorf("a request that waited past its time for a read answered %d", w.Code) |
| 1457 | } |
| 1458 | case <-time.After(10 * time.Second): |
| 1459 | t.Fatal("a request waits for a read past its time of 200ms") |
| 1460 | } |
| 1461 | |
| 1462 | // A request whose reader goes away stops waiting, and answers |
| 1463 | // nothing. |
| 1464 | h.srv.timeout = time.Hour |
| 1465 | fourth := h.publish(exporttest.SignedAt.Add(3*time.Minute), nil, renamed("Readers browse the fourth plan")) |
| 1466 | ctx, cancel := context.WithCancel(context.Background()) |
| 1467 | defer cancel() |
| 1468 | gone := serve(httptest.NewRequest("GET", "/", nil).WithContext(ctx)) |
| 1469 | eventually(t, "a request waits for the fourth generation", func() bool { return len(h.srv.loadWaiting) == 3 }) |
| 1470 | cancel() |
| 1471 | select { |
| 1472 | case w := <-gone: |
| 1473 | if w.Body.Len() != 0 { |
| 1474 | t.Errorf("a request whose reader went away answered %d", w.Code) |
| 1475 | } |
| 1476 | case <-time.After(10 * time.Second): |
| 1477 | t.Fatal("a request whose reader went away still waits") |
| 1478 | } |
| 1479 | |
| 1480 | h.srv.mu.Lock() |
| 1481 | left := len(h.srv.loads) |
| 1482 | h.srv.mu.Unlock() |
| 1483 | if left != MaxLoads { |
| 1484 | t.Errorf("%d loads may be joined; only the %d that run are wanted", left, MaxLoads) |
| 1485 | } |
| 1486 | h.publish(exporttest.SignedAt.Add(4*time.Minute), nil, renamed("Readers browse the fifth plan")) |
| 1487 | for _, g := range []export.Generation{third, fourth} { |
| 1488 | if _, err := os.Stat(g.Dir); !os.IsNotExist(err) { |
| 1489 | t.Errorf("generation %d outlived an activation after its request gave up: %v", g.Sequence, err) |
| 1490 | } |
| 1491 | } |
| 1492 | |
| 1493 | // The first two reads end, and their requests are served the newest |
| 1494 | // generation. |
| 1495 | close(hold) |
| 1496 | expect(firstServed, "Readers browse the fifth plan") |
| 1497 | expect(secondServed, "Readers browse the fifth plan") |
| 1498 | for _, g := range []export.Generation{third, fourth} { |
| 1499 | if n := loaded(g); n != 0 { |
| 1500 | t.Errorf("generation %d's export was read %d times after every request for it gave up", g.Sequence, n) |
| 1501 | } |
| 1502 | } |
| 1503 | mu.Lock() |
| 1504 | defer mu.Unlock() |
| 1505 | if len(logged) != 1 || !strings.Contains(logged[0], "deadline exceeded") { |
| 1506 | t.Errorf("the server logged %q; it logs the one request that ran out of time", logged) |
| 1507 | } |
| 1508 | } |
| 1509 | |
| 1510 | // A load that reads slowly does not hold the request that waits for it: |
| 1511 | // the request answers 503 at its deadline. With no request left waiting, |
| 1512 | // the load stops reading part way through the export, caches nothing, and |
| 1513 | // gives back its generation, which the next activation deletes. A load |
| 1514 | // that ends is kept, and the requests after it are served without another |
| 1515 | // read. |
| 1516 | func TestSlowLoadEndsWithItsRequests(t *testing.T) { |
| 1517 | h := newHarness(t) |
| 1518 | h.srv.timeout = 200 * time.Millisecond |
| 1519 | var mu sync.Mutex |
| 1520 | var logged []string |
| 1521 | h.srv.log = func(err error) { |
| 1522 | mu.Lock() |
| 1523 | defer mu.Unlock() |
| 1524 | logged = append(logged, err.Error()) |
| 1525 | } |
| 1526 | var reads atomic.Int32 |
| 1527 | h.srv.loading = func(export.Generation) { reads.Add(1) } |
| 1528 | |
| 1529 | // The active generation's export.json becomes a pipe the test writes |
| 1530 | // a few bytes at a time, as a slow disk would give it: all of it |
| 1531 | // takes about 4 seconds, twenty times the request's time. |
| 1532 | old := h.active() |
| 1533 | data, err := os.ReadFile(old.ExportPath()) |
| 1534 | if err != nil { |
| 1535 | t.Fatal(err) |
| 1536 | } |
| 1537 | if err := os.Remove(old.ExportPath()); err != nil { |
| 1538 | t.Fatal(err) |
| 1539 | } |
| 1540 | if err := syscall.Mkfifo(old.ExportPath(), 0o600); err != nil { |
| 1541 | t.Fatal(err) |
| 1542 | } |
| 1543 | piece := max(1, len(data)/200) |
| 1544 | wrote := make(chan error, 1) |
| 1545 | go func() { |
| 1546 | f, err := os.OpenFile(old.ExportPath(), os.O_WRONLY, 0) |
| 1547 | if err != nil { |
| 1548 | wrote <- err |
| 1549 | return |
| 1550 | } |
| 1551 | defer f.Close() |
| 1552 | for p := data; len(p) > 0; p = p[min(len(p), piece):] { |
| 1553 | if _, err := f.Write(p[:min(len(p), piece)]); err != nil { |
| 1554 | wrote <- err |
| 1555 | return |
| 1556 | } |
| 1557 | time.Sleep(20 * time.Millisecond) |
| 1558 | } |
| 1559 | wrote <- nil |
| 1560 | }() |
| 1561 | |
| 1562 | start := time.Now() |
| 1563 | if w := h.get("/"); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 1564 | t.Errorf("a request whose load ran past its time answered %d", w.Code) |
| 1565 | } |
| 1566 | if waited := time.Since(start); waited > 2*time.Second { |
| 1567 | t.Errorf("a request waited %v for a slow load, past its time of 200ms", waited) |
| 1568 | } |
| 1569 | select { |
| 1570 | case err := <-wrote: |
| 1571 | if !errors.Is(err, syscall.EPIPE) { |
| 1572 | t.Errorf("the load read the whole export after its request gave up: the writer ended with %v", err) |
| 1573 | } |
| 1574 | case <-time.After(10 * time.Second): |
| 1575 | t.Fatal("the load still reads the export") |
| 1576 | } |
| 1577 | eventually(t, "the load ends", func() bool { return len(h.srv.loaders) == 0 }) |
| 1578 | h.srv.mu.Lock() |
| 1579 | cached, loads := h.srv.cached, len(h.srv.loads) |
| 1580 | h.srv.mu.Unlock() |
| 1581 | if cached != nil || loads != 0 { |
| 1582 | t.Errorf("a load that stopped left a snapshot %v and %d loads", cached != nil, loads) |
| 1583 | } |
| 1584 | // The store reads the active export.json when it takes an upload. |
| 1585 | if err := os.Remove(old.ExportPath()); err != nil { |
| 1586 | t.Fatal(err) |
| 1587 | } |
| 1588 | if err := os.WriteFile(old.ExportPath(), data, 0o644); err != nil { |
| 1589 | t.Fatal(err) |
| 1590 | } |
| 1591 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 1592 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 1593 | t.Errorf("the generation a stopped load opened outlived an activation: %v", err) |
| 1594 | } |
| 1595 | |
| 1596 | h.srv.timeout = requestTimeout |
| 1597 | for range 3 { |
| 1598 | if !strings.Contains(h.page("/app/knots/oc-a000001"), "Readers browse the second plan") { |
| 1599 | t.Error("a request after the stopped load is not served the new generation") |
| 1600 | } |
| 1601 | } |
| 1602 | if n := reads.Load(); n != 2 { |
| 1603 | t.Errorf("exports were read %d times: once in part, and once for the new generation", n) |
| 1604 | } |
| 1605 | mu.Lock() |
| 1606 | defer mu.Unlock() |
| 1607 | if len(logged) != 1 || !strings.Contains(logged[0], "export to be read: context deadline exceeded") { |
| 1608 | t.Errorf("the server logged %q; it logs the one request that ran out of time", logged) |
| 1609 | } |
| 1610 | } |
| 1611 | |
| 1612 | // openFiles is the number of files the process holds open, and false |
| 1613 | // where the system does not list them. |
| 1614 | func openFiles(t *testing.T) (int, bool) { |
| 1615 | t.Helper() |
| 1616 | entries, err := os.ReadDir("/proc/self/fd") |
| 1617 | if err != nil { |
| 1618 | return 0, false |
| 1619 | } |
| 1620 | return len(entries), true |
| 1621 | } |
| 1622 | |
| 1623 | // A flood of requests while a load runs: MaxLoadWaiting of them wait, and |
| 1624 | // the rest answer 503 at once, unlogged. A waiting request holds no |
| 1625 | // generation, so the goroutines and files the server holds stay within a |
| 1626 | // bound however large the flood. Once the load ends, every request that |
| 1627 | // waited is served from its one read. |
| 1628 | func TestLoadFlood(t *testing.T) { |
| 1629 | h := newHarness(t) |
| 1630 | var reads atomic.Int32 |
| 1631 | reading, hold := make(chan struct{}, 1), make(chan struct{}) |
| 1632 | h.srv.loading = func(export.Generation) { |
| 1633 | reads.Add(1) |
| 1634 | reading <- struct{}{} |
| 1635 | <-hold |
| 1636 | } |
| 1637 | get := func(n int) chan *httptest.ResponseRecorder { |
| 1638 | served := make(chan *httptest.ResponseRecorder, n) |
| 1639 | for range n { |
| 1640 | go func() { |
| 1641 | w := httptest.NewRecorder() |
| 1642 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil)) |
| 1643 | served <- w |
| 1644 | }() |
| 1645 | } |
| 1646 | return served |
| 1647 | } |
| 1648 | |
| 1649 | first := get(1) |
| 1650 | select { |
| 1651 | case <-reading: |
| 1652 | case <-time.After(10 * time.Second): |
| 1653 | t.Fatal("no load started") |
| 1654 | } |
| 1655 | goroutines := runtime.NumGoroutine() |
| 1656 | files, listed := openFiles(t) |
| 1657 | |
| 1658 | flood := 4 * MaxLoadWaiting |
| 1659 | served := get(flood) |
| 1660 | refused := flood - (MaxLoadWaiting - 1) |
| 1661 | for range refused { |
| 1662 | if w := <-served; w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 1663 | t.Fatalf("a request past MaxLoadWaiting answered %d", w.Code) |
| 1664 | } |
| 1665 | } |
| 1666 | if n := len(h.srv.loadWaiting); n != MaxLoadWaiting { |
| 1667 | t.Errorf("%d requests wait for the load, not %d", n, MaxLoadWaiting) |
| 1668 | } |
| 1669 | const slack = 8 |
| 1670 | eventually(t, "the refused requests' goroutines end", func() bool { |
| 1671 | return runtime.NumGoroutine() <= goroutines+MaxLoadWaiting-1+slack |
| 1672 | }) |
| 1673 | if n, _ := openFiles(t); listed && n > files+slack { |
| 1674 | t.Errorf("the flood holds %d files open, %d more than before it", n, n-files) |
| 1675 | } |
| 1676 | |
| 1677 | close(hold) |
| 1678 | for range MaxLoadWaiting - 1 { |
| 1679 | if w := <-served; w.Code != http.StatusOK { |
| 1680 | t.Errorf("a request that waited for the load answered %d", w.Code) |
| 1681 | } |
| 1682 | } |
| 1683 | if w := <-first; w.Code != http.StatusOK { |
| 1684 | t.Errorf("the request that started the load answered %d", w.Code) |
| 1685 | } |
| 1686 | if n := reads.Load(); n != 1 { |
| 1687 | t.Errorf("the export was read %d times for one generation", n) |
| 1688 | } |
| 1689 | if n := len(h.srv.loadWaiting); n != 0 { |
| 1690 | t.Errorf("%d requests still hold a place among those that wait", n) |
| 1691 | } |
| 1692 | } |
| 1693 | |
| 1694 | // A request's time runs from its arrival through its rendering: a request |
| 1695 | // for a page that runs no git, held past its time before it renders, |
| 1696 | // answers 503, and the server logs it. |
| 1697 | func TestRenderingIsWithinTheDeadline(t *testing.T) { |
| 1698 | h := newHarness(t) |
| 1699 | h.page("/") |
| 1700 | h.srv.timeout = 50 * time.Millisecond |
| 1701 | var logged []string |
| 1702 | h.srv.log = func(err error) { logged = append(logged, err.Error()) } |
| 1703 | h.srv.opened = func(export.Generation) { time.Sleep(100 * time.Millisecond) } |
| 1704 | if w := h.get("/"); w.Code != http.StatusServiceUnavailable || !bytes.Equal(w.Body.Bytes(), busyPage) { |
| 1705 | t.Errorf("a request that ran out of time before it rendered answered %d", w.Code) |
| 1706 | } |
| 1707 | if len(logged) != 1 || !strings.Contains(logged[0], "rendering plan: context deadline exceeded") { |
| 1708 | t.Errorf("the server logged %q", logged) |
| 1709 | } |
| 1710 | if n := len(h.srv.budget); n != 0 { |
| 1711 | t.Errorf("a page that stopped rendering kept %d pieces of the budget", n) |
| 1712 | } |
| 1713 | } |
| 1714 | |
| 1715 | // A FIFO with a writer that sends no bytes keeps Read blocked until the |
| 1716 | // request deadline. A FIFO without a writer must not block Open. |
| 1717 | func TestStalledLoadReleasesGeneration(t *testing.T) { |
| 1718 | for _, writer := range []bool{false, true} { |
| 1719 | t.Run(fmt.Sprint(writer), func(t *testing.T) { |
| 1720 | h := newHarness(t) |
| 1721 | h.srv.timeout = 100 * time.Millisecond |
| 1722 | h.srv.log = func(error) {} |
| 1723 | old := h.active() |
| 1724 | data, err := os.ReadFile(old.ExportPath()) |
| 1725 | if err != nil { |
| 1726 | t.Fatal(err) |
| 1727 | } |
| 1728 | if err := os.Remove(old.ExportPath()); err != nil { |
| 1729 | t.Fatal(err) |
| 1730 | } |
| 1731 | if err := syscall.Mkfifo(old.ExportPath(), 0600); err != nil { |
| 1732 | t.Fatal(err) |
| 1733 | } |
| 1734 | if writer { |
| 1735 | f, err := os.OpenFile(old.ExportPath(), os.O_RDWR|syscall.O_NONBLOCK, 0) |
| 1736 | if err != nil { |
| 1737 | t.Fatal(err) |
| 1738 | } |
| 1739 | defer f.Close() |
| 1740 | if _, err := f.Write([]byte("{")); err != nil { |
| 1741 | t.Fatal(err) |
| 1742 | } |
| 1743 | } |
| 1744 | if w := h.get("/"); w.Code != http.StatusServiceUnavailable { |
| 1745 | t.Fatalf("status = %d", w.Code) |
| 1746 | } |
| 1747 | eventually(t, "the stalled worker exits", func() bool { return len(h.srv.loaders) == 0 }) |
| 1748 | h.srv.mu.Lock() |
| 1749 | cached := h.srv.cached |
| 1750 | h.srv.mu.Unlock() |
| 1751 | if cached != nil { |
| 1752 | t.Fatal("stalled load cached a snapshot") |
| 1753 | } |
| 1754 | if err := os.Remove(old.ExportPath()); err != nil { |
| 1755 | t.Fatal(err) |
| 1756 | } |
| 1757 | if err := os.WriteFile(old.ExportPath(), data, 0644); err != nil { |
| 1758 | t.Fatal(err) |
| 1759 | } |
| 1760 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan")) |
| 1761 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 1762 | t.Fatalf("generation retained: %v", err) |
| 1763 | } |
| 1764 | h.srv.timeout = requestTimeout |
| 1765 | if !strings.Contains(h.page("/app/knots/oc-a000001"), "The second plan") { |
| 1766 | t.Fatal("loader slot is not reusable") |
| 1767 | } |
| 1768 | }) |
| 1769 | } |
| 1770 | } |
| 1771 | |
| 1772 | // cancelInPhase cancels a real context on the third cancellation check |
| 1773 | // inside a named processing function. It makes cancellation during CPU |
| 1774 | // work deterministic without replacing decoding or graph traversal. |
| 1775 | type cancelInPhase struct { |
| 1776 | context.Context |
| 1777 | cancel context.CancelFunc |
| 1778 | phase string |
| 1779 | checks int |
| 1780 | } |
| 1781 | |
| 1782 | func (c *cancelInPhase) Err() error { |
| 1783 | var pcs [32]uintptr |
| 1784 | n := runtime.Callers(2, pcs[:]) |
| 1785 | frames := runtime.CallersFrames(pcs[:n]) |
| 1786 | for { |
| 1787 | frame, more := frames.Next() |
| 1788 | if strings.HasSuffix(frame.Function, c.phase) { |
| 1789 | c.checks++ |
| 1790 | if c.checks == 3 { |
| 1791 | c.cancel() |
| 1792 | } |
| 1793 | break |
| 1794 | } |
| 1795 | if !more { |
| 1796 | break |
| 1797 | } |
| 1798 | } |
| 1799 | return c.Context.Err() |
| 1800 | } |
| 1801 | |
| 1802 | func TestProcessingCancellationReleasesGeneration(t *testing.T) { |
| 1803 | for _, phase := range []string{".decodeValue", ".(*Export).ValidateContext", ".(*index).planPage", ".(*index).paths", ".(*index).milestones"} { |
| 1804 | t.Run(phase, func(t *testing.T) { |
| 1805 | h := newHarness(t) |
| 1806 | old := h.active() |
| 1807 | base, cancel := context.WithCancel(context.Background()) |
| 1808 | defer cancel() |
| 1809 | ctx := &cancelInPhase{Context: base, cancel: cancel, phase: phase} |
| 1810 | l := &load{done: make(chan struct{}), cancel: cancel} |
| 1811 | h.srv.loads[l] = struct{}{} |
| 1812 | h.srv.loaders <- struct{}{} |
| 1813 | finished := make(chan struct{}) |
| 1814 | go func() { h.srv.run(ctx, l); close(finished) }() |
| 1815 | select { |
| 1816 | case <-finished: |
| 1817 | case <-time.After(2 * time.Second): |
| 1818 | t.Fatal("processing did not stop") |
| 1819 | } |
| 1820 | if ctx.checks < 3 { |
| 1821 | t.Fatalf("phase was not reached: %d checks", ctx.checks) |
| 1822 | } |
| 1823 | if !errors.Is(l.err, context.Canceled) { |
| 1824 | t.Fatalf("load error = %v", l.err) |
| 1825 | } |
| 1826 | if h.srv.cached != nil || len(h.srv.loaders) != 0 || len(h.srv.loads) != 0 { |
| 1827 | t.Fatal("cancelled processing retained load state") |
| 1828 | } |
| 1829 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan")) |
| 1830 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 1831 | t.Fatalf("generation retained: %v", err) |
| 1832 | } |
| 1833 | if !strings.Contains(h.page("/app/knots/oc-a000001"), "The second plan") { |
| 1834 | t.Fatal("loader slot is not reusable") |
| 1835 | } |
| 1836 | }) |
| 1837 | } |
| 1838 | } |