| index 137e67d..d7148d2 100644 |
| --- a/internal/slidestest/saving_browser_test.go |
| +++ b/internal/slidestest/saving_browser_test.go |
| @@ -4,6 +4,7 @@ package slidestest |
| |
| import ( |
| "encoding/json" |
| + "fmt" |
| "io" |
| "log/slog" |
| "math/rand/v2" |
| @@ -56,10 +57,52 @@ const savingScript = `({ text, held }) => { |
| 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') |
| @@ -154,6 +197,15 @@ const savingReady = `document.documentElement.getAttribute('data-slides-fonts') |
| // |
| // 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") != "" { |
| @@ -164,11 +216,12 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) { |
| s := newSavingServer(t) |
| t.Run("playwright", func(t *testing.T) { |
| engines := []string{"chromium", "webkit"} |
| - docs, closing, large, prose, stripped := map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{} |
| + 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") |
| @@ -178,47 +231,58 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) { |
| 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}}, |
| - {"name": "prose", "docs": prose, "typing": map[string]string{"text": proseText(), "held": heldNavigation}}, |
| + {"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() |
| - t.Logf("%s", out) |
| + 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]) }) |
| - // 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). |
| + // 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, results[e+"-large"]) }) |
| + 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, results[e+"-stripped"]) |
| + 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() |
| @@ -226,12 +290,19 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) { |
| t.Error("the paste did not reach the server while the link was loading") |
| } |
| s.contains(t, prose[e], "Prosepaste") |
| - s.calm(t, results[e+"-prose"]) |
| + 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 !strings.Contains(string(out), `SAVING CLOSED {"engine":"`+e+`"}`) { |
| + 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 |
| @@ -261,7 +332,7 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) { |
| } |
| 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"})) |
| + 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 |
| @@ -273,12 +344,13 @@ func TestSavingContinuesWhileALinkIsLoading(t *testing.T) { |
| 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"})) |
| + 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, savingResults(t, out)["wkwebview-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 |
| @@ -288,12 +360,13 @@ func TestSavingContinuesWhileALinkIsLoading(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})) |
| + 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, savingResults(t, out)["wkwebview-back"]) |
| + s.calm(t, r) |
| }) |
| }) |
| } |
| @@ -303,7 +376,7 @@ func runSavingHarness(t *testing.T, bin, config string) string { |
| cmd := exec.Command(bin) |
| cmd.Env = append(os.Environ(), "DOCS_SAVING_CONFIG="+config) |
| out, err := cmd.CombinedOutput() |
| - t.Logf("%s", out) |
| + logHarness(t, string(out)) |
| if err != nil { |
| t.Fatalf("saving-webkit: %v", err) |
| } |
| @@ -312,6 +385,10 @@ func runSavingHarness(t *testing.T, bin, config string) string { |
| |
| 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 |
| @@ -335,6 +412,31 @@ type savingServer struct { |
| // 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 |
| @@ -363,7 +465,7 @@ func (s *savingServer) slow(sqid string) { |
| 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{}} |
| + 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 { |
| @@ -390,9 +492,16 @@ func newSavingServer(t *testing.T) *savingServer { |
| <-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") |
| @@ -421,6 +530,7 @@ func newSavingServer(t *testing.T) *savingServer { |
| 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 |
| } |
| @@ -446,7 +556,10 @@ func (s *savingServer) config(t *testing.T, extra map[string]any) string { |
| "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, |
| } |
| @@ -460,14 +573,56 @@ func (s *savingServer) config(t *testing.T, extra map[string]any) string { |
| 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, states []string) { |
| +func (s *savingServer) check(t *testing.T, sqid string, r *savingResult) { |
| t.Helper() |
| - if states == nil { |
| - t.Fatal("the harness reported nothing for this engine") |
| - } |
| + s.result(t, sqid, r) |
| s.mu.Lock() |
| held := s.held[sqid] |
| s.mu.Unlock() |
| @@ -475,68 +630,232 @@ func (s *savingServer) check(t *testing.T, sqid string, states []string) { |
| t.Error("no save reached the server while the link was loading: the editor stopped saving") |
| } |
| s.contains(t, sqid, savingText) |
| - s.calm(t, states) |
| + 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() |
| - 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 { |
| - t.Fatalf("the slide: %d %s", rec.Code, rec.Body.String()) |
| + body, err := s.text(sqid) |
| + if err != nil { |
| + t.Fatal(err) |
| } |
| for _, word := range strings.Fields(text) { |
| - if !strings.Contains(rec.Body.String(), word) { |
| - t.Errorf("the server's document is missing %q:\n%s", word, rec.Body.String()) |
| + 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, states []string) { |
| +func (s *savingServer) calm(t *testing.T, r *savingResult) { |
| t.Helper() |
| - if states == nil { |
| + if r == nil { |
| t.Fatal("the harness reported no save states") |
| } |
| - for _, st := range 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, states) |
| + t.Errorf("the page said %q while no request had failed (states %v)", st, r.States) |
| break |
| } |
| } |
| } |
| |
| -// savingResults reads each "SAVING RESULT {engine, states}" line. |
| -func savingResults(t *testing.T, out string) map[string][]string { |
| +// 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][]string{} |
| + results := map[string]*savingResult{} |
| + traces := map[string][]savingTrace{} |
| for _, line := range strings.Split(out, "\n") { |
| - rest, ok := strings.CutPrefix(strings.TrimSpace(line), "SAVING RESULT ") |
| - if !ok { |
| + 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 |
| } |
| - var r struct { |
| - Engine string `json:"engine"` |
| - States []string `json:"states"` |
| + 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.States |
| + 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 |