package slidestest import ( "bufio" "bytes" "compress/gzip" "context" "crypto/rand" "net/http" "net/http/httptest" "strings" "testing" "time" ) // A process that is stopping ends every open stream at once, and answers // a stream opened after that with a clean end and a reconnection delay // (internal/slides/drain.go). net/http's graceful shutdown waits for // requests in progress and cancels none of their contexts, so an open // editor or projector held the shutdown for its whole ten seconds and the // process exited 1 (Docs #94; cmd/slides's // TestStoppingWithAStreamOpenExitsAtOnce is the process half). Both kinds: // the deck's and the presentation's, which the share link's also is. func TestStreamsEndWhenTheAppDrains(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) path := sampleDeck(t, a, cookies) session, _ := startPresenting(t, a, path, cookies) srv := httptest.NewServer(a) defer srv.Close() open := func(target string) (*http.Response, *bufio.Reader) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) t.Cleanup(cancel) req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+target, nil) if err != nil { t.Fatal(err) } for _, c := range cookies { req.AddCookie(c) } res, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("open %s: %v", target, err) } t.Cleanup(func() { res.Body.Close() }) if res.StatusCode != http.StatusOK { t.Fatalf("GET %s: %d, want 200", target, res.StatusCode) } return res, bufio.NewReader(res.Body) } ended := func(r *bufio.Reader) <-chan struct{} { done := make(chan struct{}) go func() { for { if _, err := r.ReadString('\n'); err != nil { close(done) return } } }() return done } _, deck := open(path + "/stream") nextEvent(t, deck, "update") _, talk := open("/p/" + session + "/stream") nextSlideEvent(t, talk) deckEnded, talkEnded := ended(deck), ended(talk) a.app.Drain() for name, done := range map[string]<-chan struct{}{"the deck's": deckEnded, "the presentation's": talkEnded} { select { case <-done: case <-time.After(2 * time.Second): t.Errorf("%s stream was still open after the app drained", name) } } // Opened while stopping: a clean end, at once, with a reconnection // delay. Not an error status, which would end a projector's // EventSource for good. for _, target := range []string{path + "/stream", "/p/" + session + "/stream"} { res, body := open(target) got := make(chan string, 1) go func() { var b strings.Builder for { line, err := body.ReadString('\n') b.WriteString(line) if err != nil { got <- b.String() return } } }() select { case all := <-got: if !strings.Contains(all, "retry: ") || strings.Contains(all, "event: ") { t.Errorf("GET %s while draining said %q, want only a reconnection delay", target, all) } case <-time.After(2 * time.Second): t.Errorf("GET %s while draining stayed open", target) } _ = res } a.app.Drain() // twice is harmless } // The editor gzips a large save so that more of them fit a keepalive // request, the one kind WebKit still sends while a link the page opened // is loading (fixtures/save-queue.mjs, Docs #94). The server takes the // body gunzipped, under the same limits: a body expanding past a // megabyte is refused as too large, a body that is not gzip is refused // (400, as in Docs), // and so is any other encoding. func TestAPostedUpdateMayBeGzipped(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) path := createDeck(t, a, cookies, "Compressed") log, _ := getUpdates(t, a, path, 0, cookies) m := newMirror(t, sqidOf(path), log) update := m.ops(t, `[{"op":"add_slide","id":"gzipslide01","layout":"flow","template":"title"}]`) send := func(body []byte, encoding string) int { t.Helper() req := httptest.NewRequest(http.MethodPost, path+"/updates", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/octet-stream") req.Header.Set("Origin", testOrigin) req.Header.Set("Sec-Fetch-Site", "same-origin") if encoding != "" { req.Header.Set("Content-Encoding", encoding) } for _, c := range cookies { req.AddCookie(c) } rec := httptest.NewRecorder() a.ServeHTTP(rec, req) return rec.Code } gz := func(b []byte) []byte { var out bytes.Buffer w := gzip.NewWriter(&out) _, _ = w.Write(b) _ = w.Close() return out.Bytes() } if code := send(gz(update), "gzip"); code != http.StatusNoContent { t.Fatalf("a gzipped update: %d, want 204", code) } mustGet(t, a, path+"/slides/gzipslide01.html", http.StatusOK, cookies) if code := send(gz(make([]byte, 2<<20)), "gzip"); code != http.StatusRequestEntityTooLarge { t.Errorf("a gzipped body expanding past the limit: %d, want 413", code) } noise := make([]byte, (1<<20)+1024) _, _ = rand.Read(noise) if code := send(noise, "gzip"); code != http.StatusRequestEntityTooLarge && code != http.StatusBadRequest { t.Errorf("an oversized gzip body: %d, want 413 or 400", code) } // 400, as in Docs: the body is not gzip at all, which is not the 422 of // an update the core refuses. if code := send([]byte("not gzip at all"), "gzip"); code != http.StatusBadRequest { t.Errorf("a body that is not gzip: %d, want 400", code) } if code := send(gz(update)[:20], "gzip"); code != http.StatusBadRequest { t.Errorf("a truncated gzip body: %d, want 400", code) } if code := send(update, "br"); code != http.StatusUnsupportedMediaType { t.Errorf("an unsupported encoding: %d, want 415", code) } }