//go:build browser package slidestest import ( "encoding/json" "fmt" "io" "log/slog" "math/rand/v2" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "runtime" "strings" "sync" "sync/atomic" "testing" "time" "amadan.net/rastrillo/rastrillo" "amadan.net/rastrillo/rastrillo/db" slides "amadan.net/oficina/slides/internal/slides" ) // heldNavigation is the link the page opens: the server takes the request // and never answers it, as an instance that is restarting or waking does // not, until the browser goes away. const heldNavigation = "/test/held-navigation" // savingScript runs in the document page: it watches the save line, opens // the held link the way a click does, and types three words after it. // What the page showed is kept in window.__saveStates and logged, because // a page with a navigation pending cannot always be asked (Playwright's // evaluate waits for it). const savingScript = `({ text, held }) => { const line = document.querySelector('[estilo-save-status]') window.__saveStates = [] new MutationObserver(() => { const s = line.getAttribute('data-state') window.__saveStates.push(s) console.log('SAVE-STATE ' + s) }).observe(line, { attributes: true, attributeFilter: ['data-state'] }) const a = document.createElement('a') a.href = held document.body.append(a) a.click() const words = text.split(' ') let i = 0 const type = () => { const p = document.querySelector('[slides-stage] [data-block="text"] p') p.closest('[contenteditable]').focus() getSelection().selectAllChildren(p) getSelection().collapseToEnd() document.execCommand('insertText', false, ' ' + words[i]) if (++i < words.length) setTimeout(type, 300) else { window.__typed = true console.log('SAVE-TYPED') } } setTimeout(type, 300) }` // traceScript runs in every page before its own scripts: it records the // requests a save can make (POSTs, the probe's HEADs, beacons, the log's // GETs; not the static files) with their timing and how each was answered // or refused, in window.__saveTrace and as "SAVE-TRACE" console lines. The // test prints them when a scenario fails, beside the server's side of the // same saves, so a failure says which requests left the page and what // became of them (Claude Fable on Docs #94, round 3). It hands each call to the // browser's own fetch and sendBeacon unchanged and returns their results. const traceScript = `(() => { const trace = window.__saveTrace = [] const log = (e) => { e.at = Math.round(performance.timeOrigin + performance.now()) trace.push(e) console.log('SAVE-TRACE ' + JSON.stringify(e)) } const path = (u) => { try { const x = new URL(u, location.href); return x.pathname + x.search } catch { return String(u) } } const size = (b) => b == null ? 0 : (b.byteLength ?? b.size ?? String(b).length) let n = 0 const fetch = window.fetch window.fetch = function (input, init) { const u = path(typeof input === 'string' || input instanceof URL ? input : input.url) const m = ((init && init.method) || (input && input.method) || 'GET').toUpperCase() if (m === 'GET' && u.startsWith('/static/')) return fetch.apply(window, arguments) const h = new Headers((init && init.headers) || undefined) const id = ++n log({ id, ev: 'start', m, u, ka: !!(init && init.keepalive), enc: h.get('Content-Encoding') || '', size: size(init && init.body) }) const p = fetch.apply(window, arguments) p.then((r) => log({ id, ev: 'answer', status: r.status }), (err) => log({ id, ev: 'refused', err: String(err) })) return p } const beacon = navigator.sendBeacon navigator.sendBeacon = function (u, data) { const ok = beacon.apply(navigator, arguments) log({ id: ++n, ev: 'beacon', m: 'POST', u: path(u), size: size(data), ok }) return ok } })()` // typeScript types text at the end of the document's first paragraph. const typeScript = `(text) => { const p = document.querySelector('[slides-stage] [data-block="text"] p') p.closest('[contenteditable]').focus() getSelection().selectAllChildren(p) getSelection().collapseToEnd() document.execCommand('insertText', false, ' ' + text) }` // closingScript pastes a large edit, types a little more once that is on // the wire, and leaves before the little more is sent. const closingScript = `({ big, queued }) => { const end = () => { const p = document.querySelector('[slides-stage] [data-block="text"] p') p.closest('[contenteditable]').focus() getSelection().selectAllChildren(p) getSelection().collapseToEnd() } end() document.execCommand('insertText', false, ' ' + big) setTimeout(() => { end() document.execCommand('insertText', false, ' ' + queued) setTimeout(() => { const a = document.createElement('a') a.href = '/healthz' document.body.append(a) a.click() }, 50) }, 700) }` // closingTyping is what closingScript types: a paste of 46KB of random // letters, which gzips to about 28KB, so it goes as a keepalive save just // under 32KiB, and a couple of KB after it. A beacon repeating that save // (46KB raw, beside the 28KB on the wire) is over the shared 64KiB; one of // the queue alone is not. At 32.6KB the paste gzipped to under 20KB and // the repeat fitted, so the test could not fail (Claude Fable on Docs #94, // round 2). func closingTyping() map[string]string { rng := rand.New(rand.NewPCG(1, 2)) var big, queued strings.Builder big.WriteString("Bigpaste ") for big.Len() < 46000 { big.WriteByte(byte('a' + rng.IntN(26))) } queued.WriteString("Queuedbehind ") for queued.Len() < 2000 { queued.WriteByte(byte('a' + rng.IntN(26))) } return map[string]string{"big": big.String(), "queued": queued.String()} } // largeText is one word of 80,000 random letters: an edit no keepalive // save can carry, compressed or not. func largeText() string { rng := rand.New(rand.NewPCG(3, 4)) b := make([]byte, 80000) for i := range b { b[i] = byte('a' + rng.IntN(26)) } return string(b) } // proseText is a paste of 64KB of ordinary prose, as one word so the // typing script types it at once: twice what a keepalive save may carry, // and a few KB gzipped. func proseText() string { return "Prosepaste" + strings.Repeat("-a-pasted-paragraph-of-ordinary-prose", 64000/37) } // savingReady is the editor ready to type in: its fonts shown and the // first slide's text block editable. const savingReady = `document.documentElement.getAttribute('data-slides-fonts') === 'shown' && !!document.querySelector('[slides-stage] [data-block="text"] [contenteditable="true"], [slides-stage] [data-block="text"][contenteditable="true"]')` // A deck keeps saving while a link it opened is still loading, in // Chromium, in Playwright's WebKit and in WebKit's own WKWebView // (fixtures/engines/saving.mjs, fixtures/engines/saving-webkit.swift). // Docs' test (Docs #94), on Slides' editor, whose save queue is the same // code: every scenario Docs found there is Slides' too. // // WebKit refuses a page's ordinary fetch() while its main frame waits for // a navigation's answer: the promise rejects at once and no request is // sent. A link that is never answered, or answered with a download, leaves // the page on screen and editable meanwhile, and every save the editor // tried was refused like that: "Trouble saving. Retrying…", retried four // times a second, and not one request reached the server (Paul, Safari, // 2026-10-26; the edge logged no POSTs, and a reload cleared it). The // saves must arrive while the link is held, the words must be in the // server's document, and the page must never have said it was retrying, // because no request failed. // // The scenario is blind unless the link really was loading while the // saves were made, so that is checked too. // // The harnesses wait on conditions, not fixed pauses. Each scenario // watches the page at least as long as the fixed pause used to, then until // the server's view of the document (savingStatePath) holds what the // scenario waits for, for at most twenty seconds; a scenario that never // gets there fails. Any failure prints the page's requests beside the // server's side of them (explain). A fixed three seconds, and a page // closed without its unload handlers, made a one-off WebKit failure // impossible to read (Claude Fable on Docs #94, round 3). func TestSavingContinuesWhileALinkIsLoading(t *testing.T) { if _, err := os.Stat("../../fixtures/engines/node_modules/playwright"); err != nil { if os.Getenv("RASTRILLO_BROWSER_OPTIONAL") != "" { t.Skip("fixtures/engines is not installed") } t.Fatal("fixtures/engines is not installed: cd fixtures/engines && npm ci && npx playwright install chromium webkit") } s := newSavingServer(t) t.Run("playwright", func(t *testing.T) { engines := []string{"chromium", "webkit"} docs, closed, closing, large, prose, stripped := map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{} for _, e := range engines { stripped[e] = s.document(t, e+" stripped") s.strip(stripped[e]) docs[e] = s.document(t, e) closed[e] = s.document(t, e+" closed") large[e] = s.document(t, e+" large") prose[e] = s.document(t, e+" prose") closing[e] = s.document(t, e+" closing") s.holdLarge(closing[e]) } cmd := exec.Command("node", "saving.mjs") cmd.Dir = "../../fixtures/engines" cmd.Env = append(os.Environ(), "DOCS_SAVING_CONFIG="+s.config(t, map[string]any{ "docs": docs, "closed": closed, "closing": closing, "closingScript": closingScript, "closingTyping": closingTyping(), "typed": []map[string]any{ {"name": "stripped", "docs": stripped, "text": []string{"Strippedpaste" + strings.Repeat("-gzipped-and-then-stripped", 120), "Smallafter"}}, }, // want is what the scenario waits for the server to hold; with // link, saved while the link loads; with retried, a refused // save tried again will do instead. "held": []map[string]any{ {"name": "large", "docs": large, "typing": map[string]string{"text": largeText(), "held": heldNavigation}, "want": largeText()[:64], "retried": true}, {"name": "prose", "docs": prose, "typing": map[string]string{"text": proseText(), "held": heldNavigation}, "want": "Prosepaste", "link": true}, }, })) out, err := cmd.CombinedOutput() logHarness(t, string(out)) if err != nil { t.Fatalf("saving.mjs: %v", err) } results := savingResults(t, string(out)) for _, e := range engines { t.Run(e, func(t *testing.T) { s.check(t, docs[e], results[e]) }) // The same, closed as a person closes a tab, at once after the // last word: the unload handlers run, so the beacon carries // what the queue has not sent yet. Playwright's page.close() // skips them, which the held-link case above keeps as the // harsher close (Claude Fable on Docs #94, round 3). t.Run(e+"/closed", func(t *testing.T) { r := s.result(t, closed[e], results[e+"-closed"]) s.contains(t, closed[e], savingText) s.calm(t, r) }) // An edit too large for a keepalive save, even compressed, is // refused by WebKit until the link is answered: the page waits // quietly and retries, because no request has failed. "Trouble // saving" said otherwise (Claude Fable on Docs #94). t.Run(e+"/large", func(t *testing.T) { s.calm(t, s.result(t, large[e], results[e+"-large"])) }) // A gzipped save meets a server that does not gunzip it: here a // hop strips Content-Encoding, and updatesPost reads the // compressed bytes as the update and refuses them (422), as main // does, and as a rollback would. The save is sent again as it // is, and nothing is dropped (Claude Fable on Docs #94, round 2). t.Run(e+"/stripped", func(t *testing.T) { r := s.result(t, stripped[e], results[e+"-stripped"]) s.contains(t, stripped[e], "Strippedpaste Smallafter") s.calm(t, r) }) // A paste of 64KB of prose, twice what a keepalive save may // carry, goes gzipped and fits: saved while the link loads. t.Run(e+"/prose", func(t *testing.T) { r := s.result(t, prose[e], results[e+"-prose"]) s.mu.Lock() held := s.held[prose[e]] s.mu.Unlock() if held == 0 { t.Error("the paste did not reach the server while the link was loading") } s.contains(t, prose[e], "Prosepaste") s.calm(t, r) }) // Closed with a large save on the wire and more typed behind // it: the more must arrive by the unload beacon. Keepalive // saves and beacons share the browser's 64KiB, so a beacon // repeating the save on the wire was refused, and so was its // keepalive fallback (Claude Fable on Docs #94). t.Run(e+"/closing", func(t *testing.T) { if results[e+"-closing"] == nil { s.explain(t, closing[e], nil) t.Fatal("the harness never closed the page") } s.result(t, closing[e], results[e+"-closing"]) // The beacon, while the large save is still held: the // queued text arrives by itself. Without it the old page, // which outlives the hold, sends the text once the large // save is answered, so the words alone prove nothing // (Claude Fable on Docs #94, round 2). s.mu.Lock() beaconed := s.duringLarge[closing[e]] s.mu.Unlock() if beaconed == 0 { t.Error("nothing reached the server while the large save was held: the unload beacon was refused") } s.contains(t, closing[e], "Bigpaste Queuedbehind") }) } }) t.Run("wkwebview", func(t *testing.T) { if runtime.GOOS != "darwin" { t.Skip("WKWebView is macOS's") } swiftc, err := exec.LookPath("swiftc") if err != nil { t.Fatal("swiftc is not installed: xcode-select --install") } bin := filepath.Join(t.TempDir(), "saving-webkit") if out, err := exec.Command(swiftc, "-O", "-o", bin, "../../fixtures/engines/saving-webkit.swift").CombinedOutput(); err != nil { t.Fatalf("swiftc: %v\n%s", err, out) } t.Run("held-link", func(t *testing.T) { doc := s.document(t, "wkwebview") out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "held-link", "want": savingText})) s.check(t, doc, savingResults(t, out)["wkwebview"]) }) // The page leaves with a save on the wire, the server answers it // while the page is in the back/forward cache, and the page comes // back: what is typed then must still be saved. WebKit never // settles the promise of a keepalive save answered while its page // was away, and one save is on the wire at a time, so the editor // waited on it forever (save-queue.mjs, resume). t.Run("back", func(t *testing.T) { doc := s.document(t, "wkwebview back") s.slow(doc) out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "back", "want": "Before leaving After coming back"})) r := s.result(t, doc, savingResults(t, out)["wkwebview-back"]) if !strings.Contains(out, `"persisted":true`) { t.Fatal("the page was not shown again from the back/forward cache, so this check saw nothing") } s.contains(t, doc, "After coming back") s.calm(t, r) }) // Back at once, with a large paste still on the wire: the resend // may be refused while that save and the unload beacon hold // keepalive's 64KiB, and that is not a failed save (Claude Fable // on #94). Nothing is lost either. t.Run("back-quick", func(t *testing.T) { doc := s.document(t, "wkwebview back quick") s.holdLarge(doc) big := closingTyping()["big"] out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "back", "before": big, "awayMs": 300, "want": "Bigpaste After coming back"})) r := s.result(t, doc, savingResults(t, out)["wkwebview-back"]) if !strings.Contains(out, `"persisted":true`) { t.Fatal("the page was not shown again from the back/forward cache, so this check saw nothing") } s.contains(t, doc, "Bigpaste After coming back") s.calm(t, r) }) }) } func runSavingHarness(t *testing.T, bin, config string) string { t.Helper() cmd := exec.Command(bin) cmd.Env = append(os.Environ(), "DOCS_SAVING_CONFIG="+config) out, err := cmd.CombinedOutput() logHarness(t, string(out)) if err != nil { t.Fatalf("saving-webkit: %v", err) } return string(out) } const savingText = "Typed while loading" // savingStatePath, followed by a document's sqid, is the server's view of // it as JSON (savingView): what the harnesses wait on. const savingStatePath = "/test/saving-state/" type savingServer struct { rig *fontRig served http.Handler origin string cookies []*http.Cookie holding atomic.Int64 mu sync.Mutex // held counts, per document, the saves that reached the server and // were answered 2xx while the held link was still loading. held map[string]int // slowed are the documents whose saves the server answers late. slowed map[string]bool // heldLarge are the documents whose first save of more than 16KiB the // server answers three seconds late: true until it has. heldLarge map[string]bool // stripped are the documents whose saves lose their Content-Encoding // on the way in. stripped map[string]bool // holdingLarge is, per document, whether that save is being held now; // duringLarge counts the saves answered 2xx meanwhile. holdingLarge map[string]bool duringLarge map[string]int // posts are, per document, the saves that reached the server, in the // order they did. posts map[string][]*savingPost } // savingPost is one save as the server saw it. type savingPost struct { At int64 `json:"at"` // arrived, Unix ms Bytes int64 `json:"bytes"` Encoding string `json:"encoding,omitempty"` // as sent, before any stripping Type string `json:"type,omitempty"` Status int `json:"status"` // 0 until answered Took int64 `json:"took"` // ms from arrival to answer Link bool `json:"link,omitempty"` // answered while the held link was loading Large bool `json:"large,omitempty"` // the large save the server held } // savingView is what the server holds for a document, and how its saves // went. type savingView struct { Text string `json:"text"` Held int `json:"held"` DuringLarge int `json:"duringLarge"` LargeHeld bool `json:"largeHeld"` // a large save awaited, or held now Posts []savingPost `json:"posts"` } // strip makes sqid's saves lose their Content-Encoding on the way in, as // through a hop that strips it. func (s *savingServer) strip(sqid string) { s.mu.Lock() defer s.mu.Unlock() s.stripped[sqid] = true } // holdLarge makes the server answer sqid's first large save three seconds // late, as a slow upload would be. func (s *savingServer) holdLarge(sqid string) { s.mu.Lock() defer s.mu.Unlock() s.heldLarge[sqid] = true } // slow makes the server answer sqid's saves 1.5s late. func (s *savingServer) slow(sqid string) { s.mu.Lock() defer s.mu.Unlock() s.slowed[sqid] = true } func newSavingServer(t *testing.T) *savingServer { t.Helper() server := httptest.NewUnstartedServer(nil) s := &savingServer{origin: "http://" + server.Listener.Addr().String(), held: map[string]int{}, slowed: map[string]bool{}, heldLarge: map[string]bool{}, holdingLarge: map[string]bool{}, duringLarge: map[string]int{}, stripped: map[string]bool{}, posts: map[string][]*savingPost{}} logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) mailer := &fakeMailer{} mux, a, err := slides.New(d, slides.Config{KeymailServers: testKeymailServers, Origin: s.origin, InstanceKey: testInstanceKey, Mailer: mailer, AllowedAddresses: []string{allowedAddress}, Logger: logger}) if err != nil { t.Fatal(err) } t.Cleanup(func() { a.Close() }) mailer.flush = a.FlushMail served, closeFn, err := rastrillo.Handler(a.ServeOptions(rastrillo.Options{Logger: logger}, mux)) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = closeFn() }) s.served = served server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == heldNavigation { s.holding.Add(1) defer s.holding.Add(-1) <-r.Context().Done() return } if sqid, ok := strings.CutPrefix(r.URL.Path, savingStatePath); ok && r.Method == http.MethodGet { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(s.view(sqid)) return } if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/updates") { s.mu.Lock() sqid := strings.Split(r.URL.Path, "/")[2] post := &savingPost{At: time.Now().UnixMilli(), Bytes: r.ContentLength, Encoding: r.Header.Get("Content-Encoding"), Type: r.Header.Get("Content-Type")} s.posts[sqid] = append(s.posts[sqid], post) slow, large := s.slowed[sqid], s.heldLarge[sqid] && r.ContentLength > 16*1024 if s.stripped[sqid] { r.Header.Del("Content-Encoding") } if large { s.heldLarge[sqid] = false s.holdingLarge[sqid] = true } s.mu.Unlock() if slow { time.Sleep(1500 * time.Millisecond) } if large { time.Sleep(3 * time.Second) s.mu.Lock() s.holdingLarge[sqid] = false s.mu.Unlock() } during := s.holding.Load() > 0 rec := &statusRecorder{ResponseWriter: w, code: http.StatusOK} served.ServeHTTP(rec, r) s.mu.Lock() if rec.code/100 == 2 && during { s.held[sqid]++ } if rec.code/100 == 2 && !large && s.holdingLarge[sqid] { s.duringLarge[sqid]++ } post.Status, post.Took, post.Link, post.Large = rec.code, time.Now().UnixMilli()-post.At, during, large s.mu.Unlock() return } served.ServeHTTP(w, r) }) server.Start() t.Cleanup(server.Close) app := &testApp{Handler: served, mailer: mailer, db: d, mux: mux, app: a} s.cookies = signedIn(t, app, allowedAddress) s.rig = &fontRig{app: app, cookies: s.cookies, token: mintAgent(t, app, s.cookies, "saving")} return s } func (s *savingServer) document(t *testing.T, name string) string { t.Helper() return s.rig.deck(t, "Saving "+name, paperDeck) } func (s *savingServer) config(t *testing.T, extra map[string]any) string { t.Helper() config := map[string]any{ "origin": s.origin, "cookies": s.cookies, "script": savingScript, "typing": map[string]string{"text": savingText, "held": heldNavigation}, "want": savingText, "type": typeScript, "trace": traceScript, "state": savingStatePath, "page": "/edit", "ready": savingReady, } for k, v := range extra { config[k] = v } b, err := json.Marshal(config) if err != nil { t.Fatal(err) } return string(b) } // text is the server's first slide, as HTML. func (s *savingServer) text(sqid string) (string, error) { req := httptest.NewRequest(http.MethodGet, "/d/"+sqid+"/slides/slideone0001.html", nil) for _, c := range s.cookies { req.AddCookie(c) } rec := httptest.NewRecorder() s.served.ServeHTTP(rec, req) if rec.Code != http.StatusOK { return "", fmt.Errorf("the slide: %d %s", rec.Code, rec.Body.String()) } return rec.Body.String(), nil } // view is the server's side of sqid: its text, and every save that // reached it. func (s *savingServer) view(sqid string) savingView { text, err := s.text(sqid) if err != nil { text = err.Error() } s.mu.Lock() defer s.mu.Unlock() v := savingView{Text: text, Held: s.held[sqid], DuringLarge: s.duringLarge[sqid], LargeHeld: s.heldLarge[sqid] || s.holdingLarge[sqid], Posts: []savingPost{}} for _, p := range s.posts[sqid] { v.Posts = append(v.Posts, *p) } return v } // result is a scenario's harness report, which must exist and must have // got what it waited for; should the scenario fail, its story is printed. func (s *savingServer) result(t *testing.T, sqid string, r *savingResult) *savingResult { t.Helper() s.explain(t, sqid, r) if r == nil { t.Fatal("the harness reported nothing for this scenario") } if !r.Settled { t.Errorf("the harness gave up after %d ms waiting for %s", r.Ms, r.Waiting) } return r } // check is the held-link scenario's verdict: saves reached the server // while the link was loading, the words are in the server's document, and // the page never said a save had failed. func (s *savingServer) check(t *testing.T, sqid string, r *savingResult) { t.Helper() s.result(t, sqid, r) s.mu.Lock() held := s.held[sqid] s.mu.Unlock() if held == 0 { t.Error("no save reached the server while the link was loading: the editor stopped saving") } s.contains(t, sqid, savingText) s.calm(t, r) } // contains reads the first slide back from the server and checks every // word of text is in it. func (s *savingServer) contains(t *testing.T, sqid, text string) { t.Helper() body, err := s.text(sqid) if err != nil { t.Fatal(err) } for _, word := range strings.Fields(text) { if !strings.Contains(body, word) { t.Errorf("the server's document is missing %q:\n%s", word, body) } } } // calm fails if the page ever said a save failed: in these scenarios no // request does. func (s *savingServer) calm(t *testing.T, r *savingResult) { t.Helper() if r == nil { t.Fatal("the harness reported no save states") } for _, st := range r.States { if st == "retrying" || st == "failed" { t.Errorf("the page said %q while no request had failed (states %v)", st, r.States) break } } } // explain prints, should t fail, what the page sent and what the server // made of it, on one clock: the page's requests (traceScript) and every // save that reached the server, how each was answered, and the text the // server holds. So a failure says whether the saves never left the page, // left and were refused, or are still waiting for an answer. func (s *savingServer) explain(t *testing.T, sqid string, r *savingResult) { t.Cleanup(func() { if !t.Failed() { return } v := s.view(sqid) var base int64 for _, at := range []int64{firstAt(r), firstPost(v)} { if at != 0 && (base == 0 || at < base) { base = at } } var b strings.Builder if r != nil { fmt.Fprintf(&b, "The harness waited %d ms for %s (got it: %v); the save line showed %v.\n", r.Ms, r.Waiting, r.Settled, r.States) } b.WriteString("What the page sent (ms from the first request either side saw):\n") if r == nil || len(r.Trace) == 0 { b.WriteString(" nothing recorded\n") } else { // A page refused four times a second makes hundreds: the start // and the end say what happened. for i, e := range r.Trace { if n := len(r.Trace); n > 60 && i >= 40 && i < n-20 { if i == 40 { fmt.Fprintf(&b, " … %d more\n", n-60) } continue } fmt.Fprintf(&b, " %s\n", e.line(base)) } } b.WriteString("What reached the server:\n") if len(v.Posts) == 0 { b.WriteString(" no save\n") } for _, p := range v.Posts { fmt.Fprintf(&b, " %s\n", p.line(base)) } fmt.Fprintf(&b, "Saves answered 2xx while the link loaded: %d; while the large save was held: %d.\n", v.Held, v.DuringLarge) text := v.Text if len(text) > 800 { text = text[:800] + fmt.Sprintf("… (%d bytes in all)", len(v.Text)) } fmt.Fprintf(&b, "What the server holds:\n%s", text) t.Logf("%s", b.String()) }) } func firstAt(r *savingResult) int64 { if r == nil || len(r.Trace) == 0 { return 0 } return r.Trace[0].At } func firstPost(v savingView) int64 { if len(v.Posts) == 0 { return 0 } return v.Posts[0].At } func (p savingPost) line(base int64) string { enc := p.Encoding if enc == "" { enc = "identity" } what := fmt.Sprintf("+%d ms POST %d B %s %s", p.At-base, p.Bytes, enc, p.Type) if p.Large { what += ", the large save, held 3 s" } if p.Status == 0 { return what + ": not answered yet" } what += fmt.Sprintf(": answered %d after %d ms", p.Status, p.Took) if p.Link { what += ", with the link loading" } return what } // savingTrace is one entry of traceScript's record. type savingTrace struct { ID int `json:"id"` At int64 `json:"at"` Event string `json:"ev"` Method string `json:"m"` URL string `json:"u"` Keep bool `json:"ka"` Encoding string `json:"enc"` Size int `json:"size"` Status int `json:"status"` Err string `json:"err"` OK bool `json:"ok"` } func (e savingTrace) line(base int64) string { at := fmt.Sprintf("+%d ms #%d", e.At-base, e.ID) switch e.Event { case "start": how := "fetch" if e.Keep { how = "keepalive fetch" } if e.Encoding != "" { how += " " + e.Encoding } return fmt.Sprintf("%s %s %s %s, %d B", at, how, e.Method, e.URL, e.Size) case "answer": return fmt.Sprintf("%s answered %d", at, e.Status) case "refused": return fmt.Sprintf("%s refused: %s", at, e.Err) case "beacon": ok := "queued" if !e.OK { ok = "refused" } return fmt.Sprintf("%s beacon %s %s, %d B: %s", at, e.Method, e.URL, e.Size, ok) } return fmt.Sprintf("%s %s", at, e.Event) } // savingResult is one "SAVING RESULT" line: the save states the page // showed, and whether what the scenario waited for came, and when; with // the page's requests from its "SAVING TRACE" line. type savingResult struct { Engine string `json:"engine"` States []string `json:"states"` Settled bool `json:"settled"` Ms int `json:"ms"` Waiting string `json:"waiting"` Trace []savingTrace } // savingResults reads each "SAVING RESULT {engine, states, ...}" line, and // the "SAVING TRACE {engine, trace}" line beside it. func savingResults(t *testing.T, out string) map[string]*savingResult { t.Helper() results := map[string]*savingResult{} traces := map[string][]savingTrace{} for _, line := range strings.Split(out, "\n") { line = strings.TrimSpace(line) if rest, ok := strings.CutPrefix(line, "SAVING TRACE "); ok { var tr struct { Engine string `json:"engine"` Trace []savingTrace `json:"trace"` } if err := json.Unmarshal([]byte(rest), &tr); err != nil { t.Fatalf("%q: %v", line, err) } traces[tr.Engine] = tr.Trace continue } rest, ok := strings.CutPrefix(line, "SAVING RESULT ") if !ok { continue } var r savingResult if err := json.Unmarshal([]byte(rest), &r); err != nil { t.Fatalf("%q: %v", line, err) } if r.States == nil { r.States = []string{} } results[r.Engine] = &r } for engine, tr := range traces { if r := results[engine]; r != nil { r.Trace = tr } } return results } // logHarness logs a harness's output, less the request traces: those are // printed only for a scenario that fails (explain). func logHarness(t *testing.T, out string) { t.Helper() var keep []string for _, line := range strings.Split(out, "\n") { if !strings.HasPrefix(strings.TrimSpace(line), "SAVING TRACE ") { keep = append(keep, line) } } t.Logf("%s", strings.Join(keep, "\n")) } type statusRecorder struct { http.ResponseWriter code int } func (r *statusRecorder) WriteHeader(code int) { r.code = code r.ResponseWriter.WriteHeader(code) } func (r *statusRecorder) Flush() { if f, ok := r.ResponseWriter.(http.Flusher); ok { f.Flush() } }