oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

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