| 1 | //go:build browser |
| 2 | |
| 3 | package docs_test |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "math/rand/v2" |
| 10 | "net/http" |
| 11 | "net/http/httptest" |
| 12 | "os" |
| 13 | "os/exec" |
| 14 | "path/filepath" |
| 15 | "runtime" |
| 16 | "strings" |
| 17 | "sync" |
| 18 | "sync/atomic" |
| 19 | "testing" |
| 20 | "time" |
| 21 | |
| 22 | "amadan.net/rastrillo/rastrillo" |
| 23 | |
| 24 | "github.com/carlosframework/docs/internal/docs" |
| 25 | ) |
| 26 | |
| 27 | // heldNavigation is the link the page opens: the server takes the request |
| 28 | // and never answers it, as an instance that is restarting or waking does |
| 29 | // not, until the browser goes away. |
| 30 | const heldNavigation = "/test/held-navigation" |
| 31 | |
| 32 | // savingScript runs in the document page: it watches the save line, opens |
| 33 | // the held link the way a click does, and types three words after it. |
| 34 | // What the page showed is kept in window.__saveStates and logged, because |
| 35 | // a page with a navigation pending cannot always be asked (Playwright's |
| 36 | // evaluate waits for it). |
| 37 | const savingScript = `({ text, held }) => { |
| 38 | const line = document.querySelector('[estilo-save-status~="floating"]') |
| 39 | window.__saveStates = [] |
| 40 | new MutationObserver(() => { |
| 41 | const s = line.getAttribute('data-state') |
| 42 | window.__saveStates.push(s) |
| 43 | console.log('SAVE-STATE ' + s) |
| 44 | }).observe(line, { attributes: true, attributeFilter: ['data-state'] }) |
| 45 | const a = document.createElement('a') |
| 46 | a.href = held |
| 47 | document.body.append(a) |
| 48 | a.click() |
| 49 | const words = text.split(' ') |
| 50 | let i = 0 |
| 51 | const type = () => { |
| 52 | const el = document.querySelector('[docs-text]') |
| 53 | el.focus() |
| 54 | getSelection().selectAllChildren(el.querySelector('p')) |
| 55 | getSelection().collapseToEnd() |
| 56 | document.execCommand('insertText', false, ' ' + words[i]) |
| 57 | if (++i < words.length) setTimeout(type, 300) |
| 58 | else { |
| 59 | window.__typed = true |
| 60 | console.log('SAVE-TYPED') |
| 61 | } |
| 62 | } |
| 63 | setTimeout(type, 300) |
| 64 | }` |
| 65 | |
| 66 | // traceScript runs in every page before its own scripts: it records the |
| 67 | // requests a save can make (POSTs, the probe's HEADs, beacons, the log's |
| 68 | // GETs; not the static files) with their timing and how each was answered |
| 69 | // or refused, in window.__saveTrace and as "SAVE-TRACE" console lines. The |
| 70 | // test prints them when a scenario fails, beside the server's side of the |
| 71 | // same saves, so a failure says which requests left the page and what |
| 72 | // became of them (Claude Fable on #94, round 3). It hands each call to the |
| 73 | // browser's own fetch and sendBeacon unchanged and returns their results. |
| 74 | const traceScript = `(() => { |
| 75 | const trace = window.__saveTrace = [] |
| 76 | const log = (e) => { |
| 77 | e.at = Math.round(performance.timeOrigin + performance.now()) |
| 78 | trace.push(e) |
| 79 | console.log('SAVE-TRACE ' + JSON.stringify(e)) |
| 80 | } |
| 81 | const path = (u) => { try { const x = new URL(u, location.href); return x.pathname + x.search } catch { return String(u) } } |
| 82 | const size = (b) => b == null ? 0 : (b.byteLength ?? b.size ?? String(b).length) |
| 83 | let n = 0 |
| 84 | const fetch = window.fetch |
| 85 | window.fetch = function (input, init) { |
| 86 | const u = path(typeof input === 'string' || input instanceof URL ? input : input.url) |
| 87 | const m = ((init && init.method) || (input && input.method) || 'GET').toUpperCase() |
| 88 | if (m === 'GET' && u.startsWith('/static/')) return fetch.apply(window, arguments) |
| 89 | const h = new Headers((init && init.headers) || undefined) |
| 90 | const id = ++n |
| 91 | log({ id, ev: 'start', m, u, ka: !!(init && init.keepalive), enc: h.get('Content-Encoding') || '', size: size(init && init.body) }) |
| 92 | const p = fetch.apply(window, arguments) |
| 93 | p.then((r) => log({ id, ev: 'answer', status: r.status }), (err) => log({ id, ev: 'refused', err: String(err) })) |
| 94 | return p |
| 95 | } |
| 96 | const beacon = navigator.sendBeacon |
| 97 | navigator.sendBeacon = function (u, data) { |
| 98 | const ok = beacon.apply(navigator, arguments) |
| 99 | log({ id: ++n, ev: 'beacon', m: 'POST', u: path(u), size: size(data), ok }) |
| 100 | return ok |
| 101 | } |
| 102 | })()` |
| 103 | |
| 104 | // typeScript types text at the end of the document's first paragraph. |
| 105 | const typeScript = `(text) => { |
| 106 | const el = document.querySelector('[docs-text]') |
| 107 | el.focus() |
| 108 | getSelection().selectAllChildren(el.querySelector('p')) |
| 109 | getSelection().collapseToEnd() |
| 110 | document.execCommand('insertText', false, ' ' + text) |
| 111 | }` |
| 112 | |
| 113 | // closingScript pastes a large edit, types a little more once that is on |
| 114 | // the wire, and leaves before the little more is sent. |
| 115 | const closingScript = `({ big, queued }) => { |
| 116 | const el = document.querySelector('[docs-text]') |
| 117 | const end = () => { |
| 118 | el.focus() |
| 119 | getSelection().selectAllChildren(el.querySelector('p')) |
| 120 | getSelection().collapseToEnd() |
| 121 | } |
| 122 | end() |
| 123 | document.execCommand('insertText', false, ' ' + big) |
| 124 | setTimeout(() => { |
| 125 | end() |
| 126 | document.execCommand('insertText', false, ' ' + queued) |
| 127 | setTimeout(() => { |
| 128 | const a = document.createElement('a') |
| 129 | a.href = '/healthz' |
| 130 | document.body.append(a) |
| 131 | a.click() |
| 132 | }, 50) |
| 133 | }, 700) |
| 134 | }` |
| 135 | |
| 136 | // closingTyping is what closingScript types: a paste of 46KB of random |
| 137 | // letters, which gzips to about 28KB, so it goes as a keepalive save just |
| 138 | // under 32KiB, and a couple of KB after it. A beacon repeating that save |
| 139 | // (46KB raw, beside the 28KB on the wire) is over the shared 64KiB; one of |
| 140 | // the queue alone is not. At 32.6KB the paste gzipped to under 20KB and |
| 141 | // the repeat fitted, so the test could not fail (Claude Fable on #94, |
| 142 | // round 2). |
| 143 | func closingTyping() map[string]string { |
| 144 | rng := rand.New(rand.NewPCG(1, 2)) |
| 145 | var big, queued strings.Builder |
| 146 | big.WriteString("Bigpaste ") |
| 147 | for big.Len() < 46000 { |
| 148 | big.WriteByte(byte('a' + rng.IntN(26))) |
| 149 | } |
| 150 | queued.WriteString("Queuedbehind ") |
| 151 | for queued.Len() < 2000 { |
| 152 | queued.WriteByte(byte('a' + rng.IntN(26))) |
| 153 | } |
| 154 | return map[string]string{"big": big.String(), "queued": queued.String()} |
| 155 | } |
| 156 | |
| 157 | // largeText is one word of 80,000 random letters: an edit no keepalive |
| 158 | // save can carry, compressed or not. |
| 159 | func largeText() string { |
| 160 | rng := rand.New(rand.NewPCG(3, 4)) |
| 161 | b := make([]byte, 80000) |
| 162 | for i := range b { |
| 163 | b[i] = byte('a' + rng.IntN(26)) |
| 164 | } |
| 165 | return string(b) |
| 166 | } |
| 167 | |
| 168 | // proseText is a paste of 64KB of ordinary prose, as one word so the |
| 169 | // typing script types it at once: twice what a keepalive save may carry, |
| 170 | // and a few KB gzipped. |
| 171 | func proseText() string { |
| 172 | return "Prosepaste" + strings.Repeat("-a-pasted-paragraph-of-ordinary-prose", 64000/37) |
| 173 | } |
| 174 | |
| 175 | // A document keeps saving while a link it opened is still loading, in |
| 176 | // Chromium, in Playwright's WebKit and in WebKit's own WKWebView |
| 177 | // (fixtures/engines/saving.mjs, fixtures/engines/saving-webkit.swift). |
| 178 | // |
| 179 | // WebKit refuses a page's ordinary fetch() while its main frame waits for |
| 180 | // a navigation's answer: the promise rejects at once and no request is |
| 181 | // sent. A link that is never answered, or answered with a download, leaves |
| 182 | // the page on screen and editable meanwhile, and every save the editor |
| 183 | // tried was refused like that: "Trouble saving. Retrying…", retried four |
| 184 | // times a second, and not one request reached the server (Paul, Safari, |
| 185 | // 2026-10-26; the edge logged no POSTs, and a reload cleared it). The |
| 186 | // saves must arrive while the link is held, the words must be in the |
| 187 | // server's document, and the page must never have said it was retrying, |
| 188 | // because no request failed. |
| 189 | // |
| 190 | // The scenario is blind unless the link really was loading while the |
| 191 | // saves were made, so that is checked too. |
| 192 | // |
| 193 | // The harnesses wait on conditions, not fixed pauses. Each scenario |
| 194 | // watches the page at least as long as the fixed pause used to, then until |
| 195 | // the server's view of the document (savingStatePath) holds what the |
| 196 | // scenario waits for, for at most twenty seconds; a scenario that never |
| 197 | // gets there fails. Any failure prints the page's requests beside the |
| 198 | // server's side of them (explain). A fixed three seconds, and a page |
| 199 | // closed without its unload handlers, made a one-off WebKit failure |
| 200 | // impossible to read (Claude Fable on #94, round 3). |
| 201 | func TestSavingContinuesWhileALinkIsLoading(t *testing.T) { |
| 202 | if _, err := os.Stat("../../fixtures/engines/node_modules/playwright"); err != nil { |
| 203 | if os.Getenv("RASTRILLO_BROWSER_OPTIONAL") != "" { |
| 204 | t.Skip("fixtures/engines is not installed") |
| 205 | } |
| 206 | t.Fatal("fixtures/engines is not installed: cd fixtures/engines && npm ci && npx playwright install chromium webkit") |
| 207 | } |
| 208 | s := newSavingServer(t) |
| 209 | t.Run("playwright", func(t *testing.T) { |
| 210 | engines := []string{"chromium", "webkit"} |
| 211 | docs, closed, closing, large, prose, stripped := map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{}, map[string]string{} |
| 212 | for _, e := range engines { |
| 213 | stripped[e] = s.document(t, e+" stripped") |
| 214 | s.strip(stripped[e]) |
| 215 | docs[e] = s.document(t, e) |
| 216 | closed[e] = s.document(t, e+" closed") |
| 217 | large[e] = s.document(t, e+" large") |
| 218 | prose[e] = s.document(t, e+" prose") |
| 219 | closing[e] = s.document(t, e+" closing") |
| 220 | s.holdLarge(closing[e]) |
| 221 | } |
| 222 | cmd := exec.Command("node", "saving.mjs") |
| 223 | cmd.Dir = "../../fixtures/engines" |
| 224 | cmd.Env = append(os.Environ(), "DOCS_SAVING_CONFIG="+s.config(t, map[string]any{ |
| 225 | "docs": docs, |
| 226 | "closed": closed, |
| 227 | "closing": closing, |
| 228 | "closingScript": closingScript, |
| 229 | "closingTyping": closingTyping(), |
| 230 | "typed": []map[string]any{ |
| 231 | {"name": "stripped", "docs": stripped, "text": []string{"Strippedpaste" + strings.Repeat("-gzipped-and-then-stripped", 120), "Smallafter"}}, |
| 232 | }, |
| 233 | // want is what the scenario waits for the server to hold; with |
| 234 | // link, saved while the link loads; with retried, a refused |
| 235 | // save tried again will do instead. |
| 236 | "held": []map[string]any{ |
| 237 | {"name": "large", "docs": large, "typing": map[string]string{"text": largeText(), "held": heldNavigation}, "want": largeText()[:64], "retried": true}, |
| 238 | {"name": "prose", "docs": prose, "typing": map[string]string{"text": proseText(), "held": heldNavigation}, "want": "Prosepaste", "link": true}, |
| 239 | }, |
| 240 | })) |
| 241 | out, err := cmd.CombinedOutput() |
| 242 | logHarness(t, string(out)) |
| 243 | if err != nil { |
| 244 | t.Fatalf("saving.mjs: %v", err) |
| 245 | } |
| 246 | results := savingResults(t, string(out)) |
| 247 | for _, e := range engines { |
| 248 | t.Run(e, func(t *testing.T) { s.check(t, docs[e], results[e]) }) |
| 249 | // The same, closed as a person closes a tab, at once after the |
| 250 | // last word: the unload handlers run, so the beacon carries |
| 251 | // what the queue has not sent yet. Playwright's page.close() |
| 252 | // skips them, which the held-link case above keeps as the |
| 253 | // harsher close (Claude Fable on #94, round 3). |
| 254 | t.Run(e+"/closed", func(t *testing.T) { |
| 255 | r := s.result(t, closed[e], results[e+"-closed"]) |
| 256 | s.contains(t, closed[e], savingText) |
| 257 | s.calm(t, r) |
| 258 | }) |
| 259 | // An edit too large for a keepalive save, even compressed, is |
| 260 | // refused by WebKit until the link is answered: the page waits |
| 261 | // quietly and retries, because no request has failed. "Trouble |
| 262 | // saving" said otherwise (Claude Fable on #94). |
| 263 | t.Run(e+"/large", func(t *testing.T) { s.calm(t, s.result(t, large[e], results[e+"-large"])) }) |
| 264 | // A gzipped save meets a server that does not gunzip it: here a |
| 265 | // hop strips Content-Encoding, and updatesPost reads the |
| 266 | // compressed bytes as the update and refuses them, as main |
| 267 | // does, and as a rollback would. The save is sent again as it |
| 268 | // is, and nothing is dropped (Claude Fable on #94, round 2). |
| 269 | t.Run(e+"/stripped", func(t *testing.T) { |
| 270 | r := s.result(t, stripped[e], results[e+"-stripped"]) |
| 271 | s.contains(t, stripped[e], "Strippedpaste Smallafter") |
| 272 | s.calm(t, r) |
| 273 | }) |
| 274 | // A paste of 64KB of prose, twice what a keepalive save may |
| 275 | // carry, goes gzipped and fits: saved while the link loads. |
| 276 | t.Run(e+"/prose", func(t *testing.T) { |
| 277 | r := s.result(t, prose[e], results[e+"-prose"]) |
| 278 | s.mu.Lock() |
| 279 | held := s.held[prose[e]] |
| 280 | s.mu.Unlock() |
| 281 | if held == 0 { |
| 282 | t.Error("the paste did not reach the server while the link was loading") |
| 283 | } |
| 284 | s.contains(t, prose[e], "Prosepaste") |
| 285 | s.calm(t, r) |
| 286 | }) |
| 287 | // Closed with a large save on the wire and more typed behind |
| 288 | // it: the more must arrive by the unload beacon. Keepalive |
| 289 | // saves and beacons share the browser's 64KiB, so a beacon |
| 290 | // repeating the save on the wire was refused, and so was its |
| 291 | // keepalive fallback (Claude Fable on #94). |
| 292 | t.Run(e+"/closing", func(t *testing.T) { |
| 293 | if results[e+"-closing"] == nil { |
| 294 | s.explain(t, closing[e], nil) |
| 295 | t.Fatal("the harness never closed the page") |
| 296 | } |
| 297 | s.result(t, closing[e], results[e+"-closing"]) |
| 298 | // The beacon, while the large save is still held: the |
| 299 | // queued text arrives by itself. Without it the old page, |
| 300 | // which outlives the hold, sends the text once the large |
| 301 | // save is answered, so the words alone prove nothing |
| 302 | // (Claude Fable on #94, round 2). |
| 303 | s.mu.Lock() |
| 304 | beaconed := s.duringLarge[closing[e]] |
| 305 | s.mu.Unlock() |
| 306 | if beaconed == 0 { |
| 307 | t.Error("nothing reached the server while the large save was held: the unload beacon was refused") |
| 308 | } |
| 309 | s.contains(t, closing[e], "Bigpaste Queuedbehind") |
| 310 | }) |
| 311 | } |
| 312 | }) |
| 313 | t.Run("wkwebview", func(t *testing.T) { |
| 314 | if runtime.GOOS != "darwin" { |
| 315 | t.Skip("WKWebView is macOS's") |
| 316 | } |
| 317 | swiftc, err := exec.LookPath("swiftc") |
| 318 | if err != nil { |
| 319 | t.Fatal("swiftc is not installed: xcode-select --install") |
| 320 | } |
| 321 | bin := filepath.Join(t.TempDir(), "saving-webkit") |
| 322 | if out, err := exec.Command(swiftc, "-O", "-o", bin, "../../fixtures/engines/saving-webkit.swift").CombinedOutput(); err != nil { |
| 323 | t.Fatalf("swiftc: %v\n%s", err, out) |
| 324 | } |
| 325 | t.Run("held-link", func(t *testing.T) { |
| 326 | doc := s.document(t, "wkwebview") |
| 327 | out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "held-link", "want": savingText})) |
| 328 | s.check(t, doc, savingResults(t, out)["wkwebview"]) |
| 329 | }) |
| 330 | // The page leaves with a save on the wire, the server answers it |
| 331 | // while the page is in the back/forward cache, and the page comes |
| 332 | // back: what is typed then must still be saved. WebKit never |
| 333 | // settles the promise of a keepalive save answered while its page |
| 334 | // was away, and one save is on the wire at a time, so the editor |
| 335 | // waited on it forever (save-queue.mjs, resume). |
| 336 | t.Run("back", func(t *testing.T) { |
| 337 | doc := s.document(t, "wkwebview back") |
| 338 | s.slow(doc) |
| 339 | out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "back", "want": "Before leaving After coming back"})) |
| 340 | r := s.result(t, doc, savingResults(t, out)["wkwebview-back"]) |
| 341 | if !strings.Contains(out, `"persisted":true`) { |
| 342 | t.Fatal("the page was not shown again from the back/forward cache, so this check saw nothing") |
| 343 | } |
| 344 | s.contains(t, doc, "After coming back") |
| 345 | s.calm(t, r) |
| 346 | }) |
| 347 | // Back at once, with a large paste still on the wire: the resend |
| 348 | // may be refused while that save and the unload beacon hold |
| 349 | // keepalive's 64KiB, and that is not a failed save (Claude Fable |
| 350 | // on #94). Nothing is lost either. |
| 351 | t.Run("back-quick", func(t *testing.T) { |
| 352 | doc := s.document(t, "wkwebview back quick") |
| 353 | s.holdLarge(doc) |
| 354 | big := closingTyping()["big"] |
| 355 | out := runSavingHarness(t, bin, s.config(t, map[string]any{"doc": doc, "scenario": "back", "before": big, "awayMs": 300, "want": "Bigpaste After coming back"})) |
| 356 | r := s.result(t, doc, savingResults(t, out)["wkwebview-back"]) |
| 357 | if !strings.Contains(out, `"persisted":true`) { |
| 358 | t.Fatal("the page was not shown again from the back/forward cache, so this check saw nothing") |
| 359 | } |
| 360 | s.contains(t, doc, "Bigpaste After coming back") |
| 361 | s.calm(t, r) |
| 362 | }) |
| 363 | }) |
| 364 | } |
| 365 | |
| 366 | func runSavingHarness(t *testing.T, bin, config string) string { |
| 367 | t.Helper() |
| 368 | cmd := exec.Command(bin) |
| 369 | cmd.Env = append(os.Environ(), "DOCS_SAVING_CONFIG="+config) |
| 370 | out, err := cmd.CombinedOutput() |
| 371 | logHarness(t, string(out)) |
| 372 | if err != nil { |
| 373 | t.Fatalf("saving-webkit: %v", err) |
| 374 | } |
| 375 | return string(out) |
| 376 | } |
| 377 | |
| 378 | const savingText = "Typed while loading" |
| 379 | |
| 380 | // savingStatePath, followed by a document's sqid, is the server's view of |
| 381 | // it as JSON (savingView): what the harnesses wait on. |
| 382 | const savingStatePath = "/test/saving-state/" |
| 383 | |
| 384 | type savingServer struct { |
| 385 | app *docs.App |
| 386 | served http.Handler |
| 387 | origin string |
| 388 | cookies []*http.Cookie |
| 389 | holding atomic.Int64 |
| 390 | |
| 391 | mu sync.Mutex |
| 392 | // held counts, per document, the saves that reached the server and |
| 393 | // were answered 2xx while the held link was still loading. |
| 394 | held map[string]int |
| 395 | // slowed are the documents whose saves the server answers late. |
| 396 | slowed map[string]bool |
| 397 | // heldLarge are the documents whose first save of more than 16KiB the |
| 398 | // server answers three seconds late: true until it has. |
| 399 | heldLarge map[string]bool |
| 400 | // stripped are the documents whose saves lose their Content-Encoding |
| 401 | // on the way in. |
| 402 | stripped map[string]bool |
| 403 | // holdingLarge is, per document, whether that save is being held now; |
| 404 | // duringLarge counts the saves answered 2xx meanwhile. |
| 405 | holdingLarge map[string]bool |
| 406 | duringLarge map[string]int |
| 407 | // posts are, per document, the saves that reached the server, in the |
| 408 | // order they did. |
| 409 | posts map[string][]*savingPost |
| 410 | } |
| 411 | |
| 412 | // savingPost is one save as the server saw it. |
| 413 | type savingPost struct { |
| 414 | At int64 `json:"at"` // arrived, Unix ms |
| 415 | Bytes int64 `json:"bytes"` |
| 416 | Encoding string `json:"encoding,omitempty"` // as sent, before any stripping |
| 417 | Type string `json:"type,omitempty"` |
| 418 | Status int `json:"status"` // 0 until answered |
| 419 | Took int64 `json:"took"` // ms from arrival to answer |
| 420 | Link bool `json:"link,omitempty"` // answered while the held link was loading |
| 421 | Large bool `json:"large,omitempty"` // the large save the server held |
| 422 | } |
| 423 | |
| 424 | // savingView is what the server holds for a document, and how its saves |
| 425 | // went. |
| 426 | type savingView struct { |
| 427 | Text string `json:"text"` |
| 428 | Held int `json:"held"` |
| 429 | DuringLarge int `json:"duringLarge"` |
| 430 | LargeHeld bool `json:"largeHeld"` // a large save awaited, or held now |
| 431 | Posts []savingPost `json:"posts"` |
| 432 | } |
| 433 | |
| 434 | // strip makes sqid's saves lose their Content-Encoding on the way in, as |
| 435 | // through a hop that strips it. |
| 436 | func (s *savingServer) strip(sqid string) { |
| 437 | s.mu.Lock() |
| 438 | defer s.mu.Unlock() |
| 439 | s.stripped[sqid] = true |
| 440 | } |
| 441 | |
| 442 | // holdLarge makes the server answer sqid's first large save three seconds |
| 443 | // late, as a slow upload would be. |
| 444 | func (s *savingServer) holdLarge(sqid string) { |
| 445 | s.mu.Lock() |
| 446 | defer s.mu.Unlock() |
| 447 | s.heldLarge[sqid] = true |
| 448 | } |
| 449 | |
| 450 | // slow makes the server answer sqid's saves 1.5s late. |
| 451 | func (s *savingServer) slow(sqid string) { |
| 452 | s.mu.Lock() |
| 453 | defer s.mu.Unlock() |
| 454 | s.slowed[sqid] = true |
| 455 | } |
| 456 | |
| 457 | func newSavingServer(t *testing.T) *savingServer { |
| 458 | t.Helper() |
| 459 | server := httptest.NewUnstartedServer(nil) |
| 460 | 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{}} |
| 461 | app, err := docs.NewForTestWith(t, docs.Config{Origin: s.origin}) |
| 462 | if err != nil { |
| 463 | t.Fatal(err) |
| 464 | } |
| 465 | served, done, err := rastrillo.Handler(docs.ServeOptions(rastrillo.Options{}, app)) |
| 466 | if err != nil { |
| 467 | t.Fatal(err) |
| 468 | } |
| 469 | if done != nil { |
| 470 | t.Cleanup(func() { _ = done() }) |
| 471 | } |
| 472 | s.app, s.served = app, served |
| 473 | server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 474 | if r.URL.Path == heldNavigation { |
| 475 | s.holding.Add(1) |
| 476 | defer s.holding.Add(-1) |
| 477 | <-r.Context().Done() |
| 478 | return |
| 479 | } |
| 480 | if sqid, ok := strings.CutPrefix(r.URL.Path, savingStatePath); ok && r.Method == http.MethodGet { |
| 481 | w.Header().Set("Content-Type", "application/json") |
| 482 | _ = json.NewEncoder(w).Encode(s.view(sqid)) |
| 483 | return |
| 484 | } |
| 485 | if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/updates") { |
| 486 | s.mu.Lock() |
| 487 | sqid := strings.Split(r.URL.Path, "/")[2] |
| 488 | post := &savingPost{At: time.Now().UnixMilli(), Bytes: r.ContentLength, Encoding: r.Header.Get("Content-Encoding"), Type: r.Header.Get("Content-Type")} |
| 489 | s.posts[sqid] = append(s.posts[sqid], post) |
| 490 | slow, large := s.slowed[sqid], s.heldLarge[sqid] && r.ContentLength > 16*1024 |
| 491 | if s.stripped[sqid] { |
| 492 | r.Header.Del("Content-Encoding") |
| 493 | } |
| 494 | if large { |
| 495 | s.heldLarge[sqid] = false |
| 496 | s.holdingLarge[sqid] = true |
| 497 | } |
| 498 | s.mu.Unlock() |
| 499 | if slow { |
| 500 | time.Sleep(1500 * time.Millisecond) |
| 501 | } |
| 502 | if large { |
| 503 | time.Sleep(3 * time.Second) |
| 504 | s.mu.Lock() |
| 505 | s.holdingLarge[sqid] = false |
| 506 | s.mu.Unlock() |
| 507 | } |
| 508 | during := s.holding.Load() > 0 |
| 509 | rec := &statusRecorder{ResponseWriter: w, code: http.StatusOK} |
| 510 | served.ServeHTTP(rec, r) |
| 511 | s.mu.Lock() |
| 512 | if rec.code/100 == 2 && during { |
| 513 | s.held[sqid]++ |
| 514 | } |
| 515 | if rec.code/100 == 2 && !large && s.holdingLarge[sqid] { |
| 516 | s.duringLarge[sqid]++ |
| 517 | } |
| 518 | post.Status, post.Took, post.Link, post.Large = rec.code, time.Now().UnixMilli()-post.At, during, large |
| 519 | s.mu.Unlock() |
| 520 | return |
| 521 | } |
| 522 | served.ServeHTTP(w, r) |
| 523 | }) |
| 524 | server.Start() |
| 525 | t.Cleanup(server.Close) |
| 526 | s.cookies = signInCookies(t, app, "saving@example.com") |
| 527 | return s |
| 528 | } |
| 529 | |
| 530 | func (s *savingServer) document(t *testing.T, name string) string { |
| 531 | t.Helper() |
| 532 | ctx := context.Background() |
| 533 | doc, err := s.app.Store().Create(ctx, s.app.TestPerson(t, "saving@example.com"), "Saving "+name) |
| 534 | if err != nil { |
| 535 | t.Fatal(err) |
| 536 | } |
| 537 | if _, err := s.app.Store().ApplyUpdate(ctx, doc, s.app.TestActorFor(t, doc), mustRead(t, "../../fixtures/vectors/fragment/simple.bin")); err != nil { |
| 538 | t.Fatal(err) |
| 539 | } |
| 540 | return doc.Sqid |
| 541 | } |
| 542 | |
| 543 | func (s *savingServer) config(t *testing.T, extra map[string]any) string { |
| 544 | t.Helper() |
| 545 | config := map[string]any{ |
| 546 | "origin": s.origin, |
| 547 | "cookies": s.cookies, |
| 548 | "script": savingScript, |
| 549 | "typing": map[string]string{"text": savingText, "held": heldNavigation}, |
| 550 | "want": savingText, |
| 551 | "type": typeScript, |
| 552 | "trace": traceScript, |
| 553 | "state": savingStatePath, |
| 554 | } |
| 555 | for k, v := range extra { |
| 556 | config[k] = v |
| 557 | } |
| 558 | b, err := json.Marshal(config) |
| 559 | if err != nil { |
| 560 | t.Fatal(err) |
| 561 | } |
| 562 | return string(b) |
| 563 | } |
| 564 | |
| 565 | // text is the server's document, as Markdown. |
| 566 | func (s *savingServer) text(sqid string) (string, error) { |
| 567 | req := httptest.NewRequest(http.MethodGet, "/d/"+sqid+"/export.md", nil) |
| 568 | for _, c := range s.cookies { |
| 569 | req.AddCookie(c) |
| 570 | } |
| 571 | rec := httptest.NewRecorder() |
| 572 | s.served.ServeHTTP(rec, req) |
| 573 | if rec.Code != http.StatusOK { |
| 574 | return "", fmt.Errorf("export.md: %d %s", rec.Code, rec.Body.String()) |
| 575 | } |
| 576 | return rec.Body.String(), nil |
| 577 | } |
| 578 | |
| 579 | // view is the server's side of sqid: its text, and every save that |
| 580 | // reached it. |
| 581 | func (s *savingServer) view(sqid string) savingView { |
| 582 | text, err := s.text(sqid) |
| 583 | if err != nil { |
| 584 | text = err.Error() |
| 585 | } |
| 586 | s.mu.Lock() |
| 587 | defer s.mu.Unlock() |
| 588 | v := savingView{Text: text, Held: s.held[sqid], DuringLarge: s.duringLarge[sqid], LargeHeld: s.heldLarge[sqid] || s.holdingLarge[sqid], Posts: []savingPost{}} |
| 589 | for _, p := range s.posts[sqid] { |
| 590 | v.Posts = append(v.Posts, *p) |
| 591 | } |
| 592 | return v |
| 593 | } |
| 594 | |
| 595 | // result is a scenario's harness report, which must exist and must have |
| 596 | // got what it waited for; should the scenario fail, its story is printed. |
| 597 | func (s *savingServer) result(t *testing.T, sqid string, r *savingResult) *savingResult { |
| 598 | t.Helper() |
| 599 | s.explain(t, sqid, r) |
| 600 | if r == nil { |
| 601 | t.Fatal("the harness reported nothing for this scenario") |
| 602 | } |
| 603 | if !r.Settled { |
| 604 | t.Errorf("the harness gave up after %d ms waiting for %s", r.Ms, r.Waiting) |
| 605 | } |
| 606 | return r |
| 607 | } |
| 608 | |
| 609 | // check is the held-link scenario's verdict: saves reached the server |
| 610 | // while the link was loading, the words are in the server's document, and |
| 611 | // the page never said a save had failed. |
| 612 | func (s *savingServer) check(t *testing.T, sqid string, r *savingResult) { |
| 613 | t.Helper() |
| 614 | s.result(t, sqid, r) |
| 615 | s.mu.Lock() |
| 616 | held := s.held[sqid] |
| 617 | s.mu.Unlock() |
| 618 | if held == 0 { |
| 619 | t.Error("no save reached the server while the link was loading: the editor stopped saving") |
| 620 | } |
| 621 | s.contains(t, sqid, savingText) |
| 622 | s.calm(t, r) |
| 623 | } |
| 624 | |
| 625 | // contains reads the document back from the server and checks every |
| 626 | // word of text is in it. |
| 627 | func (s *savingServer) contains(t *testing.T, sqid, text string) { |
| 628 | t.Helper() |
| 629 | body, err := s.text(sqid) |
| 630 | if err != nil { |
| 631 | t.Fatal(err) |
| 632 | } |
| 633 | for _, word := range strings.Fields(text) { |
| 634 | if !strings.Contains(body, word) { |
| 635 | t.Errorf("the server's document is missing %q:\n%s", word, body) |
| 636 | } |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | // calm fails if the page ever said a save failed: in these scenarios no |
| 641 | // request does. |
| 642 | func (s *savingServer) calm(t *testing.T, r *savingResult) { |
| 643 | t.Helper() |
| 644 | if r == nil { |
| 645 | t.Fatal("the harness reported no save states") |
| 646 | } |
| 647 | for _, st := range r.States { |
| 648 | if st == "retrying" || st == "failed" { |
| 649 | t.Errorf("the page said %q while no request had failed (states %v)", st, r.States) |
| 650 | break |
| 651 | } |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | // explain prints, should t fail, what the page sent and what the server |
| 656 | // made of it, on one clock: the page's requests (traceScript) and every |
| 657 | // save that reached the server, how each was answered, and the text the |
| 658 | // server holds. So a failure says whether the saves never left the page, |
| 659 | // left and were refused, or are still waiting for an answer. |
| 660 | func (s *savingServer) explain(t *testing.T, sqid string, r *savingResult) { |
| 661 | t.Cleanup(func() { |
| 662 | if !t.Failed() { |
| 663 | return |
| 664 | } |
| 665 | v := s.view(sqid) |
| 666 | var base int64 |
| 667 | for _, at := range []int64{firstAt(r), firstPost(v)} { |
| 668 | if at != 0 && (base == 0 || at < base) { |
| 669 | base = at |
| 670 | } |
| 671 | } |
| 672 | var b strings.Builder |
| 673 | if r != nil { |
| 674 | 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) |
| 675 | } |
| 676 | b.WriteString("What the page sent (ms from the first request either side saw):\n") |
| 677 | if r == nil || len(r.Trace) == 0 { |
| 678 | b.WriteString(" nothing recorded\n") |
| 679 | } else { |
| 680 | // A page refused four times a second makes hundreds: the start |
| 681 | // and the end say what happened. |
| 682 | for i, e := range r.Trace { |
| 683 | if n := len(r.Trace); n > 60 && i >= 40 && i < n-20 { |
| 684 | if i == 40 { |
| 685 | fmt.Fprintf(&b, " … %d more\n", n-60) |
| 686 | } |
| 687 | continue |
| 688 | } |
| 689 | fmt.Fprintf(&b, " %s\n", e.line(base)) |
| 690 | } |
| 691 | } |
| 692 | b.WriteString("What reached the server:\n") |
| 693 | if len(v.Posts) == 0 { |
| 694 | b.WriteString(" no save\n") |
| 695 | } |
| 696 | for _, p := range v.Posts { |
| 697 | fmt.Fprintf(&b, " %s\n", p.line(base)) |
| 698 | } |
| 699 | fmt.Fprintf(&b, "Saves answered 2xx while the link loaded: %d; while the large save was held: %d.\n", v.Held, v.DuringLarge) |
| 700 | text := v.Text |
| 701 | if len(text) > 800 { |
| 702 | text = text[:800] + fmt.Sprintf("… (%d bytes in all)", len(v.Text)) |
| 703 | } |
| 704 | fmt.Fprintf(&b, "What the server holds:\n%s", text) |
| 705 | t.Logf("%s", b.String()) |
| 706 | }) |
| 707 | } |
| 708 | |
| 709 | func firstAt(r *savingResult) int64 { |
| 710 | if r == nil || len(r.Trace) == 0 { |
| 711 | return 0 |
| 712 | } |
| 713 | return r.Trace[0].At |
| 714 | } |
| 715 | |
| 716 | func firstPost(v savingView) int64 { |
| 717 | if len(v.Posts) == 0 { |
| 718 | return 0 |
| 719 | } |
| 720 | return v.Posts[0].At |
| 721 | } |
| 722 | |
| 723 | func (p savingPost) line(base int64) string { |
| 724 | enc := p.Encoding |
| 725 | if enc == "" { |
| 726 | enc = "identity" |
| 727 | } |
| 728 | what := fmt.Sprintf("+%d ms POST %d B %s %s", p.At-base, p.Bytes, enc, p.Type) |
| 729 | if p.Large { |
| 730 | what += ", the large save, held 3 s" |
| 731 | } |
| 732 | if p.Status == 0 { |
| 733 | return what + ": not answered yet" |
| 734 | } |
| 735 | what += fmt.Sprintf(": answered %d after %d ms", p.Status, p.Took) |
| 736 | if p.Link { |
| 737 | what += ", with the link loading" |
| 738 | } |
| 739 | return what |
| 740 | } |
| 741 | |
| 742 | // savingTrace is one entry of traceScript's record. |
| 743 | type savingTrace struct { |
| 744 | ID int `json:"id"` |
| 745 | At int64 `json:"at"` |
| 746 | Event string `json:"ev"` |
| 747 | Method string `json:"m"` |
| 748 | URL string `json:"u"` |
| 749 | Keep bool `json:"ka"` |
| 750 | Encoding string `json:"enc"` |
| 751 | Size int `json:"size"` |
| 752 | Status int `json:"status"` |
| 753 | Err string `json:"err"` |
| 754 | OK bool `json:"ok"` |
| 755 | } |
| 756 | |
| 757 | func (e savingTrace) line(base int64) string { |
| 758 | at := fmt.Sprintf("+%d ms #%d", e.At-base, e.ID) |
| 759 | switch e.Event { |
| 760 | case "start": |
| 761 | how := "fetch" |
| 762 | if e.Keep { |
| 763 | how = "keepalive fetch" |
| 764 | } |
| 765 | if e.Encoding != "" { |
| 766 | how += " " + e.Encoding |
| 767 | } |
| 768 | return fmt.Sprintf("%s %s %s %s, %d B", at, how, e.Method, e.URL, e.Size) |
| 769 | case "answer": |
| 770 | return fmt.Sprintf("%s answered %d", at, e.Status) |
| 771 | case "refused": |
| 772 | return fmt.Sprintf("%s refused: %s", at, e.Err) |
| 773 | case "beacon": |
| 774 | ok := "queued" |
| 775 | if !e.OK { |
| 776 | ok = "refused" |
| 777 | } |
| 778 | return fmt.Sprintf("%s beacon %s %s, %d B: %s", at, e.Method, e.URL, e.Size, ok) |
| 779 | } |
| 780 | return fmt.Sprintf("%s %s", at, e.Event) |
| 781 | } |
| 782 | |
| 783 | // savingResult is one "SAVING RESULT" line: the save states the page |
| 784 | // showed, and whether what the scenario waited for came, and when; with |
| 785 | // the page's requests from its "SAVING TRACE" line. |
| 786 | type savingResult struct { |
| 787 | Engine string `json:"engine"` |
| 788 | States []string `json:"states"` |
| 789 | Settled bool `json:"settled"` |
| 790 | Ms int `json:"ms"` |
| 791 | Waiting string `json:"waiting"` |
| 792 | Trace []savingTrace |
| 793 | } |
| 794 | |
| 795 | // savingResults reads each "SAVING RESULT {engine, states, ...}" line, and |
| 796 | // the "SAVING TRACE {engine, trace}" line beside it. |
| 797 | func savingResults(t *testing.T, out string) map[string]*savingResult { |
| 798 | t.Helper() |
| 799 | results := map[string]*savingResult{} |
| 800 | traces := map[string][]savingTrace{} |
| 801 | for _, line := range strings.Split(out, "\n") { |
| 802 | line = strings.TrimSpace(line) |
| 803 | if rest, ok := strings.CutPrefix(line, "SAVING TRACE "); ok { |
| 804 | var tr struct { |
| 805 | Engine string `json:"engine"` |
| 806 | Trace []savingTrace `json:"trace"` |
| 807 | } |
| 808 | if err := json.Unmarshal([]byte(rest), &tr); err != nil { |
| 809 | t.Fatalf("%q: %v", line, err) |
| 810 | } |
| 811 | traces[tr.Engine] = tr.Trace |
| 812 | continue |
| 813 | } |
| 814 | rest, ok := strings.CutPrefix(line, "SAVING RESULT ") |
| 815 | if !ok { |
| 816 | continue |
| 817 | } |
| 818 | var r savingResult |
| 819 | if err := json.Unmarshal([]byte(rest), &r); err != nil { |
| 820 | t.Fatalf("%q: %v", line, err) |
| 821 | } |
| 822 | if r.States == nil { |
| 823 | r.States = []string{} |
| 824 | } |
| 825 | results[r.Engine] = &r |
| 826 | } |
| 827 | for engine, tr := range traces { |
| 828 | if r := results[engine]; r != nil { |
| 829 | r.Trace = tr |
| 830 | } |
| 831 | } |
| 832 | return results |
| 833 | } |
| 834 | |
| 835 | // logHarness logs a harness's output, less the request traces: those are |
| 836 | // printed only for a scenario that fails (explain). |
| 837 | func logHarness(t *testing.T, out string) { |
| 838 | t.Helper() |
| 839 | var keep []string |
| 840 | for _, line := range strings.Split(out, "\n") { |
| 841 | if !strings.HasPrefix(strings.TrimSpace(line), "SAVING TRACE ") { |
| 842 | keep = append(keep, line) |
| 843 | } |
| 844 | } |
| 845 | t.Logf("%s", strings.Join(keep, "\n")) |
| 846 | } |
| 847 | |
| 848 | type statusRecorder struct { |
| 849 | http.ResponseWriter |
| 850 | code int |
| 851 | } |
| 852 | |
| 853 | func (r *statusRecorder) WriteHeader(code int) { |
| 854 | r.code = code |
| 855 | r.ResponseWriter.WriteHeader(code) |
| 856 | } |
| 857 | |
| 858 | func (r *statusRecorder) Flush() { |
| 859 | if f, ok := r.ResponseWriter.(http.Flusher); ok { |
| 860 | f.Flush() |
| 861 | } |
| 862 | } |
| 863 | |