| 1 | //go:build browser |
| 2 | |
| 3 | package slidestest |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "bytes" |
| 8 | "encoding/json" |
| 9 | "io" |
| 10 | "log/slog" |
| 11 | "net/http" |
| 12 | "net/http/httptest" |
| 13 | "os" |
| 14 | "os/exec" |
| 15 | "path/filepath" |
| 16 | "runtime" |
| 17 | "strings" |
| 18 | "sync/atomic" |
| 19 | "testing" |
| 20 | "time" |
| 21 | |
| 22 | "amadan.net/rastrillo/rastrillo" |
| 23 | "amadan.net/rastrillo/rastrillo/db" |
| 24 | |
| 25 | slides "amadan.net/oficina/slides/internal/slides" |
| 26 | ) |
| 27 | |
| 28 | // A page left the moment it has opened its live stream lets go of it at |
| 29 | // once, and when it is shown again from the back/forward cache it opens |
| 30 | // one again and catches up with what changed while it was away (Docs |
| 31 | // #86, dadf9c1: Chrome and WebKit keep left pages in that cache, each |
| 32 | // kept page held its EventSource open, and after five the next page |
| 33 | // stalled on HTTP/1.1's six connections per host). |
| 34 | // |
| 35 | // Every Slides surface that streams: the editor (the deck's live |
| 36 | // updates), the projector, the follow view, the presenter view and the |
| 37 | // remote (the presentation's). In Chromium with its back/forward cache |
| 38 | // on (fixtures/engines/leaving.mjs) and in WebKit's own WKWebView |
| 39 | // (fixtures/engines/leaving-webkit.swift), each page hidden, running no |
| 40 | // frames. The check is blind unless the page really came back from the |
| 41 | // cache, so that is checked too. |
| 42 | func TestLeavingAPageLetsGoOfItsStream(t *testing.T) { |
| 43 | if _, err := os.Stat(filepath.Join("..", "..", "fixtures", "engines", "node_modules", "playwright")); err != nil { |
| 44 | if os.Getenv("RASTRILLO_BROWSER_OPTIONAL") != "" { |
| 45 | t.Skip("fixtures/engines is not installed") |
| 46 | } |
| 47 | t.Fatal("fixtures/engines is not installed: cd fixtures/engines && npm ci && npx playwright install chromium webkit") |
| 48 | } |
| 49 | var webkitBin string |
| 50 | binDir := t.TempDir() |
| 51 | engines := map[string]func(t *testing.T) *exec.Cmd{ |
| 52 | "chromium": func(t *testing.T) *exec.Cmd { |
| 53 | cmd := exec.Command("node", "leaving.mjs") |
| 54 | cmd.Dir = filepath.Join("..", "..", "fixtures", "engines") |
| 55 | return cmd |
| 56 | }, |
| 57 | "webkit": func(t *testing.T) *exec.Cmd { |
| 58 | if runtime.GOOS != "darwin" { |
| 59 | t.Skip("WKWebView is macOS's") |
| 60 | } |
| 61 | if webkitBin == "" { |
| 62 | swiftc, err := exec.LookPath("swiftc") |
| 63 | if err != nil { |
| 64 | t.Fatal("swiftc is not installed: xcode-select --install") |
| 65 | } |
| 66 | webkitBin = filepath.Join(binDir, "leaving-webkit") |
| 67 | if out, err := exec.Command(swiftc, "-O", "-o", webkitBin, filepath.Join("..", "..", "fixtures", "engines", "leaving-webkit.swift")).CombinedOutput(); err != nil { |
| 68 | t.Fatalf("swiftc: %v\n%s", err, out) |
| 69 | } |
| 70 | } |
| 71 | return exec.Command(webkitBin) |
| 72 | }, |
| 73 | } |
| 74 | for _, engine := range []string{"chromium", "webkit"} { |
| 75 | for _, surface := range []string{"editor", "projector", "follow", "presenter", "remote"} { |
| 76 | t.Run(engine+"/"+surface, func(t *testing.T) { |
| 77 | leaveAndComeBack(t, surface, engines[engine](t)) |
| 78 | }) |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | func leaveAndComeBack(t *testing.T, surface string, cmd *exec.Cmd) { |
| 84 | t.Helper() |
| 85 | server := httptest.NewUnstartedServer(nil) |
| 86 | origin := "http://" + server.Listener.Addr().String() |
| 87 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 88 | d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| 89 | if err != nil { |
| 90 | t.Fatal(err) |
| 91 | } |
| 92 | t.Cleanup(func() { d.Close() }) |
| 93 | mailer := &fakeMailer{} |
| 94 | mux, a, err := slides.New(d, slides.Config{KeymailServers: testKeymailServers, Origin: origin, InstanceKey: testInstanceKey, Mailer: mailer, AllowedAddresses: []string{allowedAddress}, Logger: logger}) |
| 95 | if err != nil { |
| 96 | t.Fatal(err) |
| 97 | } |
| 98 | t.Cleanup(func() { a.Close() }) |
| 99 | mailer.flush = a.FlushMail |
| 100 | served, closeFn, err := rastrillo.Handler(a.ServeOptions(rastrillo.Options{Logger: logger}, mux)) |
| 101 | if err != nil { |
| 102 | t.Fatal(err) |
| 103 | } |
| 104 | t.Cleanup(func() { _ = closeFn() }) |
| 105 | var streams atomic.Int64 |
| 106 | server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 107 | if strings.HasSuffix(r.URL.Path, "/stream") { |
| 108 | streams.Add(1) |
| 109 | defer streams.Add(-1) |
| 110 | } |
| 111 | served.ServeHTTP(w, r) |
| 112 | }) |
| 113 | server.Start() |
| 114 | t.Cleanup(server.Close) |
| 115 | |
| 116 | app := &testApp{Handler: served, mailer: mailer, db: d, mux: mux, app: a} |
| 117 | cookies := signedIn(t, app, allowedAddress) |
| 118 | fr := &fontRig{app: app, cookies: cookies, token: mintAgent(t, app, cookies, "leaving")} |
| 119 | sqid := fr.deck(t, "Leaving", paperDeck) |
| 120 | |
| 121 | // What the page is, what is changed while it is away, and how a page |
| 122 | // that caught up shows it. |
| 123 | var path, caughtUp string |
| 124 | var away func() |
| 125 | next := func(session, token string) func() { |
| 126 | return func() { |
| 127 | if rec := command(t, app, session, "next", token, "", nil); rec.Code >= 400 { |
| 128 | t.Fatalf("next: %d", rec.Code) |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | switch surface { |
| 133 | case "editor": |
| 134 | path = "/d/" + sqid + "/edit" |
| 135 | caughtUp = `(document.querySelector('[slides-stage]') || { textContent: '' }).textContent.includes('Changed while away')` |
| 136 | away = func() { |
| 137 | fr.ops(t, sqid, `[{"op":"set_text","slide":"slideone0001","id":"head00000001","markdown":"Changed while away"}]`) |
| 138 | } |
| 139 | default: |
| 140 | session, token := startPresenting(t, app, "/d/"+sqid, cookies) |
| 141 | away = next(session, token) |
| 142 | switch surface { |
| 143 | case "projector": |
| 144 | path = "/p/" + session |
| 145 | caughtUp = `(document.querySelector('[slides-surface]') || { getAttribute: () => '' }).getAttribute('data-slide') === '2'` |
| 146 | case "follow": |
| 147 | path = "/s/" + mintShareLink(t, app, "/d/"+sqid, cookies) + "?follow=1" |
| 148 | caughtUp = `(document.querySelector('[slides-surface]') || { getAttribute: () => '' }).getAttribute('data-slide') === '2'` |
| 149 | case "presenter": |
| 150 | path = "/p/" + session + "/notes?t=" + token |
| 151 | caughtUp = `(document.querySelector('[presenter]') || { getAttribute: () => '' }).getAttribute('data-slide') === '2'` |
| 152 | case "remote": |
| 153 | path = "/p/" + session + "/remote?t=" + token |
| 154 | caughtUp = `(document.querySelector('[slides-remote]') || { getAttribute: () => '' }).getAttribute('data-slide') === '2'` |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | config, _ := json.Marshal(map[string]any{"origin": origin, "path": path, "caughtUp": caughtUp, "cookies": cookies}) |
| 159 | cmd.Env = append(os.Environ(), "SLIDES_LEAVING_CONFIG="+string(config)) |
| 160 | stdin, err := cmd.StdinPipe() |
| 161 | if err != nil { |
| 162 | t.Fatal(err) |
| 163 | } |
| 164 | stdout, err := cmd.StdoutPipe() |
| 165 | if err != nil { |
| 166 | t.Fatal(err) |
| 167 | } |
| 168 | var stderr bytes.Buffer |
| 169 | cmd.Stderr = &stderr |
| 170 | if err := cmd.Start(); err != nil { |
| 171 | t.Fatal(err) |
| 172 | } |
| 173 | t.Cleanup(func() { |
| 174 | _ = stdin.Close() |
| 175 | _ = cmd.Process.Kill() |
| 176 | _ = cmd.Wait() |
| 177 | if stderr.Len() > 0 { |
| 178 | t.Logf("harness stderr:\n%s", stderr.String()) |
| 179 | } |
| 180 | }) |
| 181 | lines := make(chan string, 16) |
| 182 | go func() { |
| 183 | s := bufio.NewScanner(stdout) |
| 184 | for s.Scan() { |
| 185 | lines <- s.Text() |
| 186 | } |
| 187 | close(lines) |
| 188 | }() |
| 189 | expect := func(prefix string, within time.Duration) string { |
| 190 | t.Helper() |
| 191 | deadline := time.After(within) |
| 192 | for { |
| 193 | select { |
| 194 | case l, ok := <-lines: |
| 195 | if !ok { |
| 196 | t.Fatalf("the harness ended before %q", prefix) |
| 197 | } |
| 198 | if rest, found := strings.CutPrefix(l, prefix); found { |
| 199 | return rest |
| 200 | } |
| 201 | if strings.HasPrefix(l, "LEAVING FAILED") { |
| 202 | t.Fatal(l) |
| 203 | } |
| 204 | t.Log(l) |
| 205 | case <-deadline: |
| 206 | t.Fatalf("no %q within %v", prefix, within) |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | settle := func(want int64) int64 { |
| 211 | end := time.Now().Add(3 * time.Second) |
| 212 | for streams.Load() != want && time.Now().Before(end) { |
| 213 | time.Sleep(50 * time.Millisecond) |
| 214 | } |
| 215 | return streams.Load() |
| 216 | } |
| 217 | send := func(s string) { |
| 218 | if _, err := io.WriteString(stdin, s+"\n"); err != nil { |
| 219 | t.Fatal(err) |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | expect("LEAVING LEFT", 60*time.Second) |
| 224 | if n := settle(0); n != 0 { |
| 225 | 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) |
| 226 | } |
| 227 | away() |
| 228 | send("BACK") |
| 229 | var shown struct { |
| 230 | Persisted bool `json:"persisted"` |
| 231 | CaughtUp bool `json:"caughtUp"` |
| 232 | } |
| 233 | if err := json.Unmarshal([]byte(expect("LEAVING SHOWN ", 60*time.Second)), &shown); err != nil { |
| 234 | t.Fatal(err) |
| 235 | } |
| 236 | if !shown.Persisted { |
| 237 | t.Error("the page was not restored from the back/forward cache, so this check saw nothing") |
| 238 | } |
| 239 | if !shown.CaughtUp { |
| 240 | t.Errorf("the %s shown again from the cache never caught up with what changed while it was away", surface) |
| 241 | } |
| 242 | if n := settle(1); n != 1 { |
| 243 | t.Errorf("the %s shown again from the cache has %d live streams, want 1", surface, n) |
| 244 | } |
| 245 | send("DONE") |
| 246 | } |
| 247 | |