//go:build browser package slidestest import ( "bufio" "bytes" "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "runtime" "strings" "sync/atomic" "testing" "time" "amadan.net/rastrillo/rastrillo" "amadan.net/rastrillo/rastrillo/db" slides "amadan.net/oficina/slides/internal/slides" ) // A page left the moment it has opened its live stream lets go of it at // once, and when it is shown again from the back/forward cache it opens // one again and catches up with what changed while it was away (Docs // #86, dadf9c1: Chrome and WebKit keep left pages in that cache, each // kept page held its EventSource open, and after five the next page // stalled on HTTP/1.1's six connections per host). // // Every Slides surface that streams: the editor (the deck's live // updates), the projector, the follow view, the presenter view and the // remote (the presentation's). In Chromium with its back/forward cache // on (fixtures/engines/leaving.mjs) and in WebKit's own WKWebView // (fixtures/engines/leaving-webkit.swift), each page hidden, running no // frames. The check is blind unless the page really came back from the // cache, so that is checked too. func TestLeavingAPageLetsGoOfItsStream(t *testing.T) { if _, err := os.Stat(filepath.Join("..", "..", "fixtures", "engines", "node_modules", "playwright")); err != nil { if os.Getenv("RASTRILLO_BROWSER_OPTIONAL") != "" { t.Skip("fixtures/engines is not installed") } t.Fatal("fixtures/engines is not installed: cd fixtures/engines && npm ci && npx playwright install chromium webkit") } var webkitBin string binDir := t.TempDir() engines := map[string]func(t *testing.T) *exec.Cmd{ "chromium": func(t *testing.T) *exec.Cmd { cmd := exec.Command("node", "leaving.mjs") cmd.Dir = filepath.Join("..", "..", "fixtures", "engines") return cmd }, "webkit": func(t *testing.T) *exec.Cmd { if runtime.GOOS != "darwin" { t.Skip("WKWebView is macOS's") } if webkitBin == "" { swiftc, err := exec.LookPath("swiftc") if err != nil { t.Fatal("swiftc is not installed: xcode-select --install") } webkitBin = filepath.Join(binDir, "leaving-webkit") if out, err := exec.Command(swiftc, "-O", "-o", webkitBin, filepath.Join("..", "..", "fixtures", "engines", "leaving-webkit.swift")).CombinedOutput(); err != nil { t.Fatalf("swiftc: %v\n%s", err, out) } } return exec.Command(webkitBin) }, } for _, engine := range []string{"chromium", "webkit"} { for _, surface := range []string{"editor", "projector", "follow", "presenter", "remote"} { t.Run(engine+"/"+surface, func(t *testing.T) { leaveAndComeBack(t, surface, engines[engine](t)) }) } } } func leaveAndComeBack(t *testing.T, surface string, cmd *exec.Cmd) { t.Helper() server := httptest.NewUnstartedServer(nil) origin := "http://" + server.Listener.Addr().String() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) mailer := &fakeMailer{} mux, a, err := slides.New(d, slides.Config{KeymailServers: testKeymailServers, Origin: origin, InstanceKey: testInstanceKey, Mailer: mailer, AllowedAddresses: []string{allowedAddress}, Logger: logger}) if err != nil { t.Fatal(err) } t.Cleanup(func() { a.Close() }) mailer.flush = a.FlushMail served, closeFn, err := rastrillo.Handler(a.ServeOptions(rastrillo.Options{Logger: logger}, mux)) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = closeFn() }) var streams atomic.Int64 server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasSuffix(r.URL.Path, "/stream") { streams.Add(1) defer streams.Add(-1) } served.ServeHTTP(w, r) }) server.Start() t.Cleanup(server.Close) app := &testApp{Handler: served, mailer: mailer, db: d, mux: mux, app: a} cookies := signedIn(t, app, allowedAddress) fr := &fontRig{app: app, cookies: cookies, token: mintAgent(t, app, cookies, "leaving")} sqid := fr.deck(t, "Leaving", paperDeck) // What the page is, what is changed while it is away, and how a page // that caught up shows it. var path, caughtUp string var away func() next := func(session, token string) func() { return func() { if rec := command(t, app, session, "next", token, "", nil); rec.Code >= 400 { t.Fatalf("next: %d", rec.Code) } } } switch surface { case "editor": path = "/d/" + sqid + "/edit" caughtUp = `(document.querySelector('[slides-stage]') || { textContent: '' }).textContent.includes('Changed while away')` away = func() { fr.ops(t, sqid, `[{"op":"set_text","slide":"slideone0001","id":"head00000001","markdown":"Changed while away"}]`) } default: session, token := startPresenting(t, app, "/d/"+sqid, cookies) away = next(session, token) switch surface { case "projector": path = "/p/" + session caughtUp = `(document.querySelector('[slides-surface]') || { getAttribute: () => '' }).getAttribute('data-slide') === '2'` case "follow": path = "/s/" + mintShareLink(t, app, "/d/"+sqid, cookies) + "?follow=1" caughtUp = `(document.querySelector('[slides-surface]') || { getAttribute: () => '' }).getAttribute('data-slide') === '2'` case "presenter": path = "/p/" + session + "/notes?t=" + token caughtUp = `(document.querySelector('[presenter]') || { getAttribute: () => '' }).getAttribute('data-slide') === '2'` case "remote": path = "/p/" + session + "/remote?t=" + token caughtUp = `(document.querySelector('[slides-remote]') || { getAttribute: () => '' }).getAttribute('data-slide') === '2'` } } config, _ := json.Marshal(map[string]any{"origin": origin, "path": path, "caughtUp": caughtUp, "cookies": cookies}) cmd.Env = append(os.Environ(), "SLIDES_LEAVING_CONFIG="+string(config)) stdin, err := cmd.StdinPipe() if err != nil { t.Fatal(err) } stdout, err := cmd.StdoutPipe() if err != nil { t.Fatal(err) } var stderr bytes.Buffer cmd.Stderr = &stderr if err := cmd.Start(); err != nil { t.Fatal(err) } t.Cleanup(func() { _ = stdin.Close() _ = cmd.Process.Kill() _ = cmd.Wait() if stderr.Len() > 0 { t.Logf("harness stderr:\n%s", stderr.String()) } }) lines := make(chan string, 16) go func() { s := bufio.NewScanner(stdout) for s.Scan() { lines <- s.Text() } close(lines) }() expect := func(prefix string, within time.Duration) string { t.Helper() deadline := time.After(within) for { select { case l, ok := <-lines: if !ok { t.Fatalf("the harness ended before %q", prefix) } if rest, found := strings.CutPrefix(l, prefix); found { return rest } if strings.HasPrefix(l, "LEAVING FAILED") { t.Fatal(l) } t.Log(l) case <-deadline: t.Fatalf("no %q within %v", prefix, within) } } } settle := func(want int64) int64 { end := time.Now().Add(3 * time.Second) for streams.Load() != want && time.Now().Before(end) { time.Sleep(50 * time.Millisecond) } return streams.Load() } send := func(s string) { if _, err := io.WriteString(stdin, s+"\n"); err != nil { t.Fatal(err) } } expect("LEAVING LEFT", 60*time.Second) if n := settle(0); n != 0 { t.Errorf("the %s was left and %d live streams are still open: a page in the back/forward cache is holding a connection", surface, n) } away() send("BACK") var shown struct { Persisted bool `json:"persisted"` CaughtUp bool `json:"caughtUp"` } if err := json.Unmarshal([]byte(expect("LEAVING SHOWN ", 60*time.Second)), &shown); err != nil { t.Fatal(err) } if !shown.Persisted { t.Error("the page was not restored from the back/forward cache, so this check saw nothing") } if !shown.CaughtUp { t.Errorf("the %s shown again from the cache never caught up with what changed while it was away", surface) } if n := settle(1); n != 1 { t.Errorf("the %s shown again from the cache has %d live streams, want 1", surface, n) } send("DONE") }