package slidestest // Clips (scenes and clips spec §2, §4; plan call R3, Review Focus 5): a // short muted video uploaded to a deck with the picture of its first // frame as its poster, served in ranges so a browser can seek it, and // drawn as that poster wherever no video plays: scripts off, a // thumbnail, the PDF. import ( "bytes" "context" "encoding/json" "fmt" "image" "image/color" "image/png" "io" "net/http" "net/http/httptest" "net/url" "strings" "sync" "testing" "time" "amadan.net/rastrillo/rastrillo/blobs" "amadan.net/oficina/slides/internal/slides/deck" "amadan.net/oficina/slides/internal/slides/layout" ) // fakeWebM opens as a WebM does (an EBML header whose DocType is webm), // so it registers as a clip, and is nothing a browser can play after // that: Review Focus 5's video that won't play. func fakeWebM() []byte { head := []byte{ 0x1a, 0x45, 0xdf, 0xa3, 0x9f, 0x42, 0x86, 0x81, 0x01, 0x42, 0xf7, 0x81, 0x01, 0x42, 0xf2, 0x81, 0x04, 0x42, 0xf3, 0x81, 0x08, 0x42, 0x82, 0x84, 'w', 'e', 'b', 'm', 0x42, 0x87, 0x81, 0x04, 0x42, 0x85, 0x81, 0x02, } return append(head, bytes.Repeat([]byte("not a frame of video "), 64)...) } // colourPNG is a 2 by 2 PNG of one colour: a picture whose bytes are // not onePixelPNG's. func colourPNG(t *testing.T, c color.Color) []byte { t.Helper() img := image.NewRGBA(image.Rect(0, 0, 2, 2)) for x := 0; x < 2; x++ { for y := 0; y < 2; y++ { img.Set(x, y, c) } } var b bytes.Buffer if err := png.Encode(&b, img); err != nil { t.Fatal(err) } return b.Bytes() } // clipAlt is the clip's description, which its poster carries. const clipAlt = "A screen recording" // uploadClip runs the editor's clip upload over HTTP: the poster first, // a decorative picture, then the video naming it. It returns both // records the server validated. func uploadClip(t *testing.T, a *testApp, deckPath string, cookies []*http.Cookie, video []byte) (rec, poster map[string]any) { t.Helper() posterKey := stageUpload(t, a, deckPath, cookies, "clip.png", "image/png", onePixelPNG) reg := postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"clip.png","width":1,"height":1,"alt":"","decorative":true}`, posterKey), cookies) if reg.Code != http.StatusOK { t.Fatalf("register the poster: %d\n%s", reg.Code, reg.Body) } poster = jsonBody(t, reg) key := stageUpload(t, a, deckPath, cookies, "clip.webm", "video/webm", video) reg = postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"clip.webm","width":320,"height":180,"alt":%q,"poster":%q,"duration":1500}`, key, clipAlt, poster["ref"]), cookies) if reg.Code != http.StatusOK { t.Fatalf("register the clip: %d\n%s", reg.Code, reg.Body) } return jsonBody(t, reg), poster } // clipFixture is clipDeck's deck: the clip's two records and its slides. type clipFixture struct { sqid string video, poster map[string]any } // clipDeck is a deck over the API showing video as a clip: // // - slide press1: the clip played on a press (box A), and a heading; // - slide loop2: the clip in a loop; // - slide once3: the clip played once; // - slide after4: a heading. func clipDeck(t *testing.T, a *testApp, cookies []*http.Cookie, token string, video []byte) clipFixture { t.Helper() f := clipFixture{sqid: apiDeck(t, a, token, "Clips")} f.video, f.poster = uploadClip(t, a, "/d/"+f.sqid, cookies, video) view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+f.sqid, token, "", http.StatusOK) var ops []string for _, s := range view["slides"].([]any) { ops = append(ops, `{"op":"remove_slide","id":`+quote(s.(map[string]any)["id"].(string))+`}`) } ops = append(ops, fmt.Sprintf(`{"op":"register_asset","id":%q,"ref":%q,"name":"clip.png","width":1,"height":1,"alt":""}`, f.poster["id"], f.poster["ref"]), fmt.Sprintf(`{"op":"register_asset","id":%q,"ref":%q,"name":"clip.webm","width":320,"height":180,"alt":%q,"poster":%q,"duration":1500}`, f.video["id"], f.video["ref"], clipAlt, f.video["poster"])) clip := func(slide, block, play string) []string { return []string{ `{"op":"add_slide","id":"` + slide + `","layout":"canvas"}`, `{"op":"add_block","slide":"` + slide + `","id":"` + block + `","type":"clip","box":` + boxA + `,"props":{"asset":` + quote(f.video["id"].(string)) + `,"play":"` + play + `"}}`, } } ops = append(ops, clip("press1", "clippress", "press")...) ops = append(ops, `{"op":"add_block","slide":"press1","id":"presshead","type":"heading","box":{"x":0.1,"y":0.75,"w":0.8,"h":0.1},"props":{"level":2},"markdown":"Pressed"}`) ops = append(ops, clip("loop2", "cliploop", "loop")...) ops = append(ops, clip("once3", "cliponce", "once")...) ops = append(ops, `{"op":"add_slide","id":"after4","layout":"flow","template":"title"}`, `{"op":"add_block","slide":"after4","id":"afterhead","type":"heading","region":"heading","props":{"level":1},"markdown":"After"}`) apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+f.sqid+"/ops", token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK) return f } // TestClipUploadsAreRefused: a clip is an MP4 or a WebM of at most // 50 MiB with a poster this deck already holds, a PNG or WebP. Each // refusal is a code, and spends nothing: the receipt is still there for // the registration that gets it right. func TestClipUploadsAreRefused(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) deckPath := createDeck(t, a, cookies, "Clips") hash := hashOf(fakeWebM()) for _, c := range []struct { name, body string want int code string }{ {"a QuickTime movie", `{"name":"x.mov","size":10,"type":"video/quicktime","hash":"` + hash + `"}`, http.StatusUnprocessableEntity, "unsupported_type"}, {"over 50 MiB", `{"name":"x.webm","size":52428801,"type":"video/webm","hash":"` + hash + `"}`, http.StatusRequestEntityTooLarge, "too_large"}, {"over 20 MiB as a picture", `{"name":"x.png","size":20971521,"type":"image/png","hash":"` + hash + `"}`, http.StatusRequestEntityTooLarge, "too_large"}, } { rec := postJSON(t, a, deckPath+"/uploads", c.body, cookies) if rec.Code != c.want || jsonBody(t, rec)["error"] != c.code { t.Errorf("%s: %d %s, want %d %s", c.name, rec.Code, rec.Body, c.want, c.code) } } // 50 MiB exactly is a clip. if rec := postJSON(t, a, deckPath+"/uploads", `{"name":"x.mp4","size":52428800,"type":"video/mp4","hash":"`+hash+`"}`, cookies); rec.Code != http.StatusOK { t.Errorf("a 50 MiB clip: %d %s", rec.Code, rec.Body) } // The bytes that arrive are held to the limit too, whatever was said. signed := jsonBody(t, postJSON(t, a, deckPath+"/uploads", `{"name":"x.webm","size":10,"type":"video/webm","hash":"`+hash+`"}`, cookies)) big := append(fakeWebM(), make([]byte, 50<<20)...) if put := putBytes(t, a, signed["url"].(string), "video/webm", big, cookies); put.Code != http.StatusRequestEntityTooLarge { t.Errorf("a PUT of more than 50 MiB: %d, want 413", put.Code) } posterKey := stageUpload(t, a, deckPath, cookies, "p.png", "image/png", onePixelPNG) poster := jsonBody(t, postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"p.png","alt":"","decorative":true}`, posterKey), cookies)) svgKey := stageUpload(t, a, deckPath, cookies, "p.svg", "image/svg+xml", []byte(``)) svg := jsonBody(t, postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"p.svg","alt":"","decorative":true}`, svgKey), cookies)) other := createDeck(t, a, cookies, "Another") otherKey := stageUpload(t, a, other, cookies, "o.png", "image/png", colourPNG(t, color.RGBA{R: 200, A: 255})) elsewhere := jsonBody(t, postJSON(t, a, other+"/assets", fmt.Sprintf(`{"ref":%q,"name":"o.png","alt":"","decorative":true}`, otherKey), cookies)) register := func(key, fields string) *httptest.ResponseRecorder { return postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"x.webm","width":320,"height":180,"alt":""%s}`, key, fields), cookies) } // A picture staged as a video is not a video; nor is Matroska that // is not WebM. pngAsVideo := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", onePixelPNG) if rec := register(pngAsVideo, fmt.Sprintf(`,"poster":%q`, poster["ref"])); rec.Code != http.StatusUnprocessableEntity || jsonBody(t, rec)["error"] != "not_a_video" { t.Errorf("a PNG staged as a WebM: %d %s, want 422 not_a_video", rec.Code, rec.Body) } mkv := bytes.Replace(fakeWebM(), []byte{0x42, 0x82, 0x84, 'w', 'e', 'b', 'm'}, []byte{0x42, 0x82, 0x84, 'm', 'k', 'v', 'x'}, 1) mkvKey := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", mkv) if rec := register(mkvKey, fmt.Sprintf(`,"poster":%q`, poster["ref"])); rec.Code != http.StatusUnprocessableEntity || jsonBody(t, rec)["error"] != "not_a_video" { t.Errorf("a Matroska file: %d %s, want 422 not_a_video", rec.Code, rec.Body) } // A video needs a poster: one this deck verified, a PNG or WebP. key := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", fakeWebM()) for name, fields := range map[string]string{ "no poster": ``, "an empty poster": `,"poster":""`, "a poster nobody registered": `,"poster":"` + strings.Repeat("ab", 32) + `"`, "another deck's poster": fmt.Sprintf(`,"poster":%q`, elsewhere["ref"]), "an SVG poster": fmt.Sprintf(`,"poster":%q`, svg["ref"]), "a poster with a slash": `,"poster":"a/b"`, } { if rec := register(key, fields); rec.Code != http.StatusUnprocessableEntity || jsonBody(t, rec)["error"] != "poster_required" { t.Errorf("%s: %d %s, want 422 poster_required", name, rec.Code, rec.Body) } } // And with one, the record names it, with its length. rec := register(key, fmt.Sprintf(`,"poster":%q,"duration":1500`, poster["ref"])) if rec.Code != http.StatusOK { t.Fatalf("a clip with its poster: %d %s", rec.Code, rec.Body) } out := jsonBody(t, rec) if out["ref"] != hashOf(fakeWebM()) || out["poster"] != poster["ref"] || out["duration"] != float64(1500) || out["width"] != float64(320) { t.Errorf("the clip's record is %v", out) } // A negative or absurd length is no length. key = stageUpload(t, a, deckPath, cookies, "y.webm", "video/webm", append(fakeWebM(), 'y')) if out := jsonBody(t, register(key, fmt.Sprintf(`,"poster":%q,"duration":-4`, poster["ref"]))); out["duration"] != float64(0) { t.Errorf("a negative length is %v, want 0", out["duration"]) } } // TestAClipIsServedInRanges: the video's bytes come back as a picture's // do, under the deck's capability and its sniffed type, and in ranges, // so a browser can seek. func TestAClipIsServedInRanges(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) token := mintAgent(t, a, cookies, "clips") f := clipDeck(t, a, cookies, token, fakeWebM()) at := "/d/" + f.sqid + "/assets/" + f.video["ref"].(string) whole := mustGet(t, a, at, http.StatusOK, cookies) if ct := whole.Header().Get("Content-Type"); ct != "video/webm" { t.Errorf("Content-Type %q, want video/webm", ct) } if ar := whole.Header().Get("Accept-Ranges"); ar != "bytes" { t.Errorf("Accept-Ranges %q, want bytes", ar) } if !bytes.Equal(whole.Body.Bytes(), fakeWebM()) { t.Errorf("the whole clip is %d bytes, want %d", whole.Body.Len(), len(fakeWebM())) } req := httptest.NewRequest(http.MethodGet, at, nil) req.Header.Set("Range", "bytes=4-9") for _, c := range cookies { req.AddCookie(c) } part := httptest.NewRecorder() a.ServeHTTP(part, req) if part.Code != http.StatusPartialContent || !bytes.Equal(part.Body.Bytes(), fakeWebM()[4:10]) { t.Errorf("bytes 4-9: %d %x", part.Code, part.Body.Bytes()) } if cr := part.Header().Get("Content-Range"); cr != fmt.Sprintf("bytes 4-9/%d", len(fakeWebM())) { t.Errorf("Content-Range %q", cr) } // The poster is a picture like any other. if ct := mustGet(t, a, "/d/"+f.sqid+"/assets/"+f.poster["ref"].(string), http.StatusOK, cookies).Header().Get("Content-Type"); ct != "image/png" { t.Errorf("the poster's Content-Type is %q", ct) } // A share link and a presentation read it under their own capability. share := "/s/" + mintShareLink(t, a, "/d/"+f.sqid, cookies) mustGet(t, a, share+"/assets/"+f.video["ref"].(string), http.StatusOK, nil) session, _ := startPresenting(t, a, "/d/"+f.sqid, cookies) mustGet(t, a, "/p/"+session+"/assets/"+f.video["ref"].(string), http.StatusOK, nil) } // TestAClipsPosterInPicturesAndPDF: wherever no video plays, a clip is // its poster, described by the clip's text: the scriptless viewer, a // thumbnail and the PDF. The pages carry the video's address for the // script that plays it, a clip played on a press marks that press, and // the presenting windows fetch the video with the talk. func TestAClipsPosterInPicturesAndPDF(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) token := mintAgent(t, a, cookies, "clips") f := clipDeck(t, a, cookies, token, fakeWebM()) deckPath := "/d/" + f.sqid posterAt := func(base string) string { return base + "/assets/" + f.poster["ref"].(string) } videoAt := func(base string) string { return base + "/assets/" + f.video["ref"].(string) } for _, vp := range []string{"", "&vp=phone"} { section := slideSection(t, mustGet(t, a, deckPath+"?slide=1"+vp, http.StatusOK, cookies).Body.String()) for _, want := range []string{ `data-block="clip" data-id="clippress" data-clip="press" data-clip-src="` + videoAt(deckPath) + `"`, `` + clipAlt + ``, } { if !strings.Contains(section, want) { t.Errorf("viewer%s: the slide lacks %s:\n%s", vp, want, section) } } if strings.Contains(section, "`) { t.Errorf("the press is not marked:\n%s", first.HTML) } if strings.Contains(first.HTML, `data-id="clippress" data-clip="press" data-clip-src="`+videoAt("/p/"+session)+`" data-press`) { t.Errorf("the clip itself waits for its press:\n%s", first.HTML) } if payload.Slides[1].Presses != 0 || payload.Slides[3].Clips != nil { t.Errorf("the loop takes %d presses; a slide with no clip fetches %v", payload.Slides[1].Presses, payload.Slides[3].Clips) } } // TestAStagedClipComesBackToWhoStagedIt: the editor draws a clip's // poster from its bytes as this app serves them back while staged (the // page's policy loads no blob: media). A staged picture does not come // back, nor a clip once it is registered, nor an address nobody staged. func TestAStagedClipComesBackToWhoStagedIt(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) deckPath := createDeck(t, a, cookies, "Staged") key := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", fakeWebM()) back := mustGet(t, a, deckPath+"/uploads/"+key, http.StatusOK, cookies) if back.Header().Get("Content-Type") != "video/webm" || back.Header().Get("Cache-Control") != "no-store" || !bytes.Equal(back.Body.Bytes(), fakeWebM()) { t.Errorf("the staged clip comes back as %v, %d bytes", back.Header(), back.Body.Len()) } // Signed out, it is the sign-in door. mustGet(t, a, deckPath+"/uploads/"+key, http.StatusSeeOther, nil) picture := stageUpload(t, a, deckPath, cookies, "p.png", "image/png", onePixelPNG) mustGet(t, a, deckPath+"/uploads/"+picture, http.StatusNotFound, cookies) mustGet(t, a, deckPath+"/uploads/"+strings.Repeat("cd", 32), http.StatusNotFound, cookies) other := createDeck(t, a, cookies, "Other") mustGet(t, a, other+"/uploads/"+key, http.StatusNotFound, cookies) poster := jsonBody(t, postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"p.png","alt":"","decorative":true}`, picture), cookies)) if rec := postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"x.webm","poster":%q}`, key, poster["ref"]), cookies); rec.Code != http.StatusOK { t.Fatalf("register: %d %s", rec.Code, rec.Body) } mustGet(t, a, deckPath+"/uploads/"+key, http.StatusNotFound, cookies) } // unseekableStore is a store whose reader cannot seek, as the platform's // bucket behind ThroughApp and a sealed store are, counting each read of // one ref and the bytes it gave. type unseekableStore struct { blobs.Store mu sync.Mutex watch string gets int bytes int64 // slow holds each read of the watched ref this long, so requests // that arrive together overlap. slow time.Duration } func (s *unseekableStore) Get(ctx context.Context, hash string) (io.ReadCloser, error) { s.mu.Lock() slow := s.slow if hash != s.watch { slow = 0 } s.mu.Unlock() time.Sleep(slow) rc, err := s.Store.Get(ctx, hash) if err != nil { return nil, err } defer rc.Close() raw, err := io.ReadAll(rc) if err != nil { return nil, err } s.mu.Lock() defer s.mu.Unlock() if hash == s.watch { s.gets++ s.bytes += int64(len(raw)) } return io.NopCloser(bytes.NewReader(raw)), nil } func (s *unseekableStore) counts() (int, int64) { s.mu.Lock() defer s.mu.Unlock() return s.gets, s.bytes } // TestAClipFromAStoreThatCannotSeekIsReadOnce: a store that cannot // start part way is read once per clip, into a cache on disk, and every // range after that comes from the cache, reading the store no more. func TestAClipFromAStoreThatCannotSeekIsReadOnce(t *testing.T) { store := &unseekableStore{Store: dirStore(t)} a := newAppWithStore(t, store) cookies := signedIn(t, a, allowedAddress) token := mintAgent(t, a, cookies, "clips") video := append(fakeWebM(), bytes.Repeat([]byte{7}, 64<<10)...) f := clipDeck(t, a, cookies, token, video) ref := f.video["ref"].(string) store.mu.Lock() store.watch = ref store.mu.Unlock() at := "/d/" + f.sqid + "/assets/" + ref ranged := func(spec string, from, to int) { t.Helper() req := httptest.NewRequest(http.MethodGet, at, nil) req.Header.Set("Range", spec) for _, c := range cookies { req.AddCookie(c) } rec := httptest.NewRecorder() a.ServeHTTP(rec, req) if rec.Code != http.StatusPartialContent || !bytes.Equal(rec.Body.Bytes(), video[from:to+1]) { t.Fatalf("%s: %d, %d bytes", spec, rec.Code, rec.Body.Len()) } } ranged("bytes=10-20", 10, 20) if gets, n := store.counts(); gets != 1 || n != int64(len(video)) { t.Errorf("the first range read the store %d times, %d bytes; want once, %d", gets, n, len(video)) } ranged("bytes=30000-40000", 30000, 40000) ranged(fmt.Sprintf("bytes=%d-", len(video)-5), len(video)-5, len(video)-1) if gets, _ := store.counts(); gets != 1 { t.Errorf("later ranges read the store again: %d reads", gets) } whole := mustGet(t, a, at, http.StatusOK, cookies) if !bytes.Equal(whole.Body.Bytes(), video) || whole.Header().Get("Content-Type") != "video/webm" { t.Errorf("the whole clip from the cache is %d bytes, %s", whole.Body.Len(), whole.Header().Get("Content-Type")) } } // TestAClipsPosterIsAtMost4MiB: a poster is a still, held to a still's // 4 MiB at registration, exactly 4 MiB taken. func TestAClipsPosterIsAtMost4MiB(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) deckPath := createDeck(t, a, cookies, "Posters") poster := func(size int) string { body := append(append([]byte{}, onePixelPNG...), make([]byte, size-len(onePixelPNG))...) key := stageUpload(t, a, deckPath, cookies, "p.png", "image/png", body) return jsonBody(t, postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"p.png","alt":"","decorative":true}`, key), cookies))["ref"].(string) } big, fits := poster(4<<20+1), poster(4<<20) key := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", fakeWebM()) register := func(p string) *httptest.ResponseRecorder { return postJSON(t, a, deckPath+"/assets", fmt.Sprintf(`{"ref":%q,"name":"x.webm","poster":%q}`, key, p), cookies) } if rec := register(big); rec.Code != http.StatusUnprocessableEntity || jsonBody(t, rec)["error"] != "poster_too_large" || jsonBody(t, rec)["message"] == "" { t.Errorf("a poster of 4 MiB and a byte: %d %s, want 422 poster_too_large", rec.Code, rec.Body) } if rec := register(fits); rec.Code != http.StatusOK { t.Errorf("a poster of 4 MiB: %d %s", rec.Code, rec.Body) } } // TestAClipsDescriptionIsItsPosters: the description written on a clip // block is its poster's text in HTML and in the PDF, as an image's is; // decorative is empty; with neither, the video's own. func TestAClipsDescriptionIsItsPosters(t *testing.T) { a := newAppWithStore(t, dirStore(t)) cookies := signedIn(t, a, allowedAddress) token := mintAgent(t, a, cookies, "clips") f := clipDeck(t, a, cookies, token, fakeWebM()) apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+f.sqid+"/ops", token, `{"ops":[{"op":"set_block","slide":"press1","id":"clippress","props":{"alt":"Paul opens a deck"}},`+ `{"op":"set_block","slide":"loop2","id":"cliploop","props":{"decorative":true}}]}`, http.StatusOK) for slide, want := range map[int]string{1: "Paul opens a deck", 2: "", 3: clipAlt} { section := slideSection(t, mustGet(t, a, fmt.Sprintf("/d/%s?slide=%d", f.sqid, slide), http.StatusOK, cookies).Body.String()) if !strings.Contains(section, `alt="`+want+`"`) { t.Errorf("slide %d's poster is not described %q:\n%s", slide, want, section) } } view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+f.sqid, token, "", http.StatusOK) raw, _ := json.Marshal(view) var d deck.Deck if err := json.Unmarshal(raw, &d); err != nil { t.Fatal(err) } for i, want := range []string{"Paul opens a deck", "", clipAlt} { p, _, err := layout.Layout(&d, i) if err != nil { t.Fatal(err) } for _, op := range p.Ops { if im, ok := op.(layout.Image); ok && im.Alt != want { t.Errorf("the PDF's slide %d describes its poster %q, want %q", i+1, im.Alt, want) } } } } // rangeOf asks target for one range and checks it is want[from:to+1]. func rangeOf(t *testing.T, a *testApp, cookies []*http.Cookie, target string, want []byte, from, to int) error { req := httptest.NewRequest(http.MethodGet, target, nil) req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", from, to)) for _, c := range cookies { req.AddCookie(c) } rec := httptest.NewRecorder() a.ServeHTTP(rec, req) if rec.Code != http.StatusPartialContent || !bytes.Equal(rec.Body.Bytes(), want[from:to+1]) { return fmt.Errorf("bytes %d-%d: %d, %d bytes", from, to, rec.Code, rec.Body.Len()) } return nil } // TestAStagedClipFromAStoreThatCannotSeekIsReadOnce: the editor reads a // staged clip back in ranges to draw its poster; on a store that cannot // seek the first fills the cache and the next reads the store no more, // both answered. func TestAStagedClipFromAStoreThatCannotSeekIsReadOnce(t *testing.T) { store := &unseekableStore{Store: dirStore(t)} a := newAppWithStore(t, store) cookies := signedIn(t, a, allowedAddress) deckPath := createDeck(t, a, cookies, "Staged") video := append(fakeWebM(), bytes.Repeat([]byte{9}, 32<<10)...) key := stageUpload(t, a, deckPath, cookies, "x.webm", "video/webm", video) store.mu.Lock() store.watch = hashOf(video) // where blobs.Dir put the staged bytes store.mu.Unlock() for _, r := range [][2]int{{0, 99}, {20000, 30000}, {len(video) - 10, len(video) - 1}} { if err := rangeOf(t, a, cookies, deckPath+"/uploads/"+key, video, r[0], r[1]); err != nil { t.Error(err) } } if gets, n := store.counts(); gets != 1 || n != int64(len(video)) { t.Errorf("three staged ranges read the store %d times, %d bytes; want once, %d", gets, n, len(video)) } } // TestConcurrentRangesOfAClipReadTheStoreOnce: ranges of one clip that // arrive together, before any is cached, wait on one fill. func TestConcurrentRangesOfAClipReadTheStoreOnce(t *testing.T) { store := &unseekableStore{Store: dirStore(t)} a := newAppWithStore(t, store) cookies := signedIn(t, a, allowedAddress) token := mintAgent(t, a, cookies, "clips") video := append(fakeWebM(), bytes.Repeat([]byte{5}, 48<<10)...) f := clipDeck(t, a, cookies, token, video) ref := f.video["ref"].(string) store.mu.Lock() store.watch, store.slow = ref, 150*time.Millisecond store.mu.Unlock() const n = 8 errs := make(chan error, n) var wg sync.WaitGroup for i := 0; i < n; i++ { wg.Add(1) go func(i int) { defer wg.Done() from := i * 4000 errs <- rangeOf(t, a, cookies, "/d/"+f.sqid+"/assets/"+ref, video, from, from+999) }(i) } wg.Wait() close(errs) for err := range errs { if err != nil { t.Error(err) } } if gets, _ := store.counts(); gets != 1 { t.Errorf("%d ranges at once read the store %d times, want once", n, gets) } }