| 1 | //go:build browser |
| 2 | |
| 3 | package docs_test |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "encoding/json" |
| 10 | "io" |
| 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 | |
| 24 | "github.com/carlosframework/docs/internal/docs" |
| 25 | ) |
| 26 | |
| 27 | // A document left before the editor has drawn a frame lets go of its live |
| 28 | // stream at once, and when it is shown again from the back/forward cache |
| 29 | // it opens one again and catches up with what it missed (branch review on |
| 30 | // #86: the editor registered its pagehide handler after its first frames, |
| 31 | // so a page left sooner, or hidden and running no frames, kept its stream |
| 32 | // open in the cache, holding an HTTP/1.1 connection for nobody). |
| 33 | // |
| 34 | // In Chromium with its back/forward cache on (fixtures/engines/leaving.mjs) |
| 35 | // and in WebKit's own WKWebView (fixtures/engines/leaving-webkit.swift), |
| 36 | // each page hidden, running no frames, and leaving the moment the editor |
| 37 | // opens its stream. The check is blind unless the page really came back |
| 38 | // from the cache, so that is checked too. |
| 39 | func TestLeavingADocumentEarlyLetsGoOfItsStream(t *testing.T) { |
| 40 | if _, err := os.Stat("../../fixtures/engines/node_modules/playwright"); err != nil { |
| 41 | if os.Getenv("RASTRILLO_BROWSER_OPTIONAL") != "" { |
| 42 | t.Skip("fixtures/engines is not installed") |
| 43 | } |
| 44 | t.Fatal("fixtures/engines is not installed: cd fixtures/engines && npm ci && npx playwright install chromium webkit") |
| 45 | } |
| 46 | t.Run("chromium", func(t *testing.T) { |
| 47 | cmd := exec.Command("node", "leaving.mjs") |
| 48 | cmd.Dir = "../../fixtures/engines" |
| 49 | leaveAndComeBack(t, cmd) |
| 50 | }) |
| 51 | t.Run("webkit", func(t *testing.T) { |
| 52 | if runtime.GOOS != "darwin" { |
| 53 | t.Skip("WKWebView is macOS's") |
| 54 | } |
| 55 | swiftc, err := exec.LookPath("swiftc") |
| 56 | if err != nil { |
| 57 | t.Fatal("swiftc is not installed: xcode-select --install") |
| 58 | } |
| 59 | bin := filepath.Join(t.TempDir(), "leaving-webkit") |
| 60 | if out, err := exec.Command(swiftc, "-O", "-o", bin, "../../fixtures/engines/leaving-webkit.swift").CombinedOutput(); err != nil { |
| 61 | t.Fatalf("swiftc: %v\n%s", err, out) |
| 62 | } |
| 63 | leaveAndComeBack(t, exec.Command(bin)) |
| 64 | }) |
| 65 | } |
| 66 | |
| 67 | func leaveAndComeBack(t *testing.T, cmd *exec.Cmd) { |
| 68 | t.Helper() |
| 69 | server := httptest.NewUnstartedServer(nil) |
| 70 | origin := "http://" + server.Listener.Addr().String() |
| 71 | app, err := docs.NewForTestWith(t, docs.Config{Origin: origin}) |
| 72 | if err != nil { |
| 73 | t.Fatal(err) |
| 74 | } |
| 75 | served, done, err := rastrillo.Handler(docs.ServeOptions(rastrillo.Options{}, app)) |
| 76 | if err != nil { |
| 77 | t.Fatal(err) |
| 78 | } |
| 79 | if done != nil { |
| 80 | t.Cleanup(func() { _ = done() }) |
| 81 | } |
| 82 | var streams atomic.Int64 |
| 83 | server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 84 | if strings.HasSuffix(r.URL.Path, "/stream") { |
| 85 | streams.Add(1) |
| 86 | defer streams.Add(-1) |
| 87 | } |
| 88 | served.ServeHTTP(w, r) |
| 89 | }) |
| 90 | server.Start() |
| 91 | t.Cleanup(server.Close) |
| 92 | |
| 93 | ctx := context.Background() |
| 94 | doc, err := app.Store().Create(ctx, app.TestPerson(t, "leaving@example.com"), "Leaving") |
| 95 | if err != nil { |
| 96 | t.Fatal(err) |
| 97 | } |
| 98 | update, err := os.ReadFile("../../fixtures/vectors/fragment/simple.bin") |
| 99 | if err != nil { |
| 100 | t.Fatal(err) |
| 101 | } |
| 102 | if _, err := app.Store().ApplyUpdate(ctx, doc, app.TestActorFor(t, doc), update); err != nil { |
| 103 | t.Fatal(err) |
| 104 | } |
| 105 | cookies := signInCookies(t, app, "leaving@example.com") |
| 106 | const remote = "A collaborator" |
| 107 | config, _ := json.Marshal(map[string]any{"origin": origin, "doc": doc.Sqid, "cookies": cookies, "remote": remote}) |
| 108 | cmd.Env = append(os.Environ(), "DOCS_LEAVING_CONFIG="+string(config)) |
| 109 | stdin, err := cmd.StdinPipe() |
| 110 | if err != nil { |
| 111 | t.Fatal(err) |
| 112 | } |
| 113 | stdout, err := cmd.StdoutPipe() |
| 114 | if err != nil { |
| 115 | t.Fatal(err) |
| 116 | } |
| 117 | var stderr bytes.Buffer |
| 118 | cmd.Stderr = &stderr |
| 119 | if err := cmd.Start(); err != nil { |
| 120 | t.Fatal(err) |
| 121 | } |
| 122 | t.Cleanup(func() { |
| 123 | _ = stdin.Close() |
| 124 | _ = cmd.Process.Kill() |
| 125 | _ = cmd.Wait() |
| 126 | if stderr.Len() > 0 { |
| 127 | t.Logf("harness stderr:\n%s", stderr.String()) |
| 128 | } |
| 129 | }) |
| 130 | lines := make(chan string, 16) |
| 131 | go func() { |
| 132 | s := bufio.NewScanner(stdout) |
| 133 | for s.Scan() { |
| 134 | lines <- s.Text() |
| 135 | } |
| 136 | close(lines) |
| 137 | }() |
| 138 | expect := func(prefix string, within time.Duration) string { |
| 139 | t.Helper() |
| 140 | deadline := time.After(within) |
| 141 | for { |
| 142 | select { |
| 143 | case l, ok := <-lines: |
| 144 | if !ok { |
| 145 | t.Fatalf("the harness ended before %q", prefix) |
| 146 | } |
| 147 | if rest, found := strings.CutPrefix(l, prefix); found { |
| 148 | return rest |
| 149 | } |
| 150 | if strings.HasPrefix(l, "LEAVING FAILED") { |
| 151 | t.Fatal(l) |
| 152 | } |
| 153 | t.Log(l) |
| 154 | case <-deadline: |
| 155 | t.Fatalf("no %q within %v", prefix, within) |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | settle := func(want int64) int64 { |
| 160 | end := time.Now().Add(3 * time.Second) |
| 161 | for streams.Load() != want && time.Now().Before(end) { |
| 162 | time.Sleep(50 * time.Millisecond) |
| 163 | } |
| 164 | return streams.Load() |
| 165 | } |
| 166 | send := func(s string) { |
| 167 | if _, err := io.WriteString(stdin, s+"\n"); err != nil { |
| 168 | t.Fatal(err) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | expect("LEAVING LEFT", 60*time.Second) |
| 173 | if n := settle(0); n != 0 { |
| 174 | t.Errorf("the document was left and %d live streams are still open: a page in the back/forward cache is holding a connection", n) |
| 175 | } |
| 176 | // A collaborator's edit while the page is away. |
| 177 | req := httptest.NewRequest(http.MethodPost, "/d/"+doc.Sqid+"/updates", bytes.NewReader(mustRead(t, "../../fixtures/vectors/fragment/remote-bold.bin"))) |
| 178 | req.Header.Set("Content-Type", "application/octet-stream") |
| 179 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 180 | for _, c := range cookies { |
| 181 | req.AddCookie(c) |
| 182 | } |
| 183 | rec := httptest.NewRecorder() |
| 184 | served.ServeHTTP(rec, req) |
| 185 | if rec.Code/100 != 2 { |
| 186 | t.Fatalf("collaborator's POST: %d %s", rec.Code, rec.Body.String()) |
| 187 | } |
| 188 | send("BACK") |
| 189 | var shown struct { |
| 190 | Persisted bool `json:"persisted"` |
| 191 | CaughtUp bool `json:"caughtUp"` |
| 192 | } |
| 193 | if err := json.Unmarshal([]byte(expect("LEAVING SHOWN ", 60*time.Second)), &shown); err != nil { |
| 194 | t.Fatal(err) |
| 195 | } |
| 196 | if !shown.Persisted { |
| 197 | t.Error("the page was not restored from the back/forward cache, so this check saw nothing") |
| 198 | } |
| 199 | if !shown.CaughtUp { |
| 200 | t.Error("the page shown again from the cache never caught up with the edit made while it was away") |
| 201 | } |
| 202 | if n := settle(1); n != 1 { |
| 203 | t.Errorf("the page shown again from the cache has %d live streams, want 1", n) |
| 204 | } |
| 205 | send("DONE") |
| 206 | } |
| 207 | |
| 208 | func mustRead(t *testing.T, path string) []byte { |
| 209 | t.Helper() |
| 210 | b, err := os.ReadFile(path) |
| 211 | if err != nil { |
| 212 | t.Fatal(err) |
| 213 | } |
| 214 | return b |
| 215 | } |
| 216 | |