oficina / slides Public

Slides: one clip cache entry per ref, filled once, never unlinked in use

The clip cache's get looks up and opens a completed entry under its
lock and uses it; a miss claims the key, and concurrent misses wait on
that one fill instead of filling again. Registered clips are keyed by
their content hash and staged ones by their staging key, so repeated
staged ranges read the store once. The file just renamed into place is
never removed: the earlier fill dropped the old entry by path after the
rename and unlinked the new file, a 500 on the second staged range.
Eviction takes only older entries, and a response already reading one
reads on to the end.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ebb85cf057e25e8c9101759c9ee8be8064f0e016 parent ca5f92b
5 files changed, +325 −150
  • internal/slides/assets.go +16 −18
  • internal/slides/clipcache.go +74 −56
  • internal/slides/clipcache_test.go +97 −42
  • internal/slides/clips.go +52 −34
  • internal/slidestest/clips_test.go +86 −0
diff --git a/internal/slides/assets.go b/internal/slides/assets.go
index 303f7cb..1af15fb 100644
--- a/internal/slides/assets.go
+++ b/internal/slides/assets.go
@@ -849,11 +849,11 @@ func (a *app) serveAsset(w http.ResponseWriter, r *http.Request, d Deck) {
return
}
defer h.Close(r.Context())
- registered := false
+ registered, video := false, false
for _, asset := range view.Assets {
if asset.Ref == ref {
registered = true
- break
+ video = video || asset.Video()
}
}
if !registered {
@@ -877,16 +877,16 @@ func (a *app) serveAsset(w http.ResponseWriter, r *http.Request, d Deck) {
return
}
- // A clip already in the cache (clipcache.go) is served from it, and
- // the store is not read at all.
+ // A clip's video (clips.go) is served in ranges from the clip cache
+ // (clipcache.go), which reads the store once for it, whoever asks
+ // and however many at once.
cache := a.clipCacheFor()
- if f, kind, ok := cache.cached(ref); ok {
- defer f.Close()
+ if video {
assetCaching(w, ref)
if notModified(w, r, ref) {
return
}
- serveVideo(w, r, kind, f)
+ a.serveCachedVideo(w, r, cache, ref, videoLoad(r.Context(), store, ref))
return
}
@@ -912,9 +912,10 @@ func (a *app) serveAsset(w http.ResponseWriter, r *http.Request, d Deck) {
return
}
head = head[:n]
- // A clip's video (clips.go) first: no picture opens as one does.
+ // Bytes that open as a video, under an asset with no poster (an op
+ // written by hand), are still a video: no picture opens as one does.
kind := sniffVideo(head)
- video := kind != ""
+ video = kind != ""
if !video {
kind = sniffImage(head)
}
@@ -927,15 +928,12 @@ func (a *app) serveAsset(w http.ResponseWriter, r *http.Request, d Deck) {
return
}
if video {
- // A store that seeks is served from where it is; any other
- // fills the cache once, and is served from that.
- body, done, err := cachedVideo(cache, ref, kind, head, rc, true)
- if err != nil {
- a.fail(w, r, "cache a clip", err)
- return
- }
- defer done()
- serveVideo(w, r, kind, body)
+ a.serveCachedVideo(w, r, cache, ref, func() (string, io.Reader, func(), error) {
+ if rs, ok := rc.(io.ReadSeeker); ok {
+ return kind, rs, func() {}, nil
+ }
+ return kind, io.MultiReader(bytes.NewReader(head), rc), func() {}, nil
+ })
return
}
assetHeaders(w, kind)
diff --git a/internal/slides/clipcache.go b/internal/slides/clipcache.go
index ad9b0bb..88dca4e 100644
--- a/internal/slides/clipcache.go
+++ b/internal/slides/clipcache.go
@@ -12,8 +12,10 @@
// served from the file with http.ServeContent. Nothing is ever held
// whole in memory.
//
-// The cache is bounded: 1 GiB in all, the least recently served video
-// dropped first. It is this process's alone and starts empty: a
+// One entry per key: a clip's content hash, or a staged upload's
+// staging key. Requests that miss together wait on one fill; a filled
+// entry is used by everyone after. The cache is bounded: 1 GiB in all,
+// the least recently served video dropped first. It is this process's alone and starts empty: a
// directory of its own under the system's temporary directory, removed
// when the app closes, unless Config.ClipCache names one to use.
package slides
@@ -81,61 +83,69 @@ func (c *clipCache) mkdir() error {
func (c *clipCache) path(ref string) string { return filepath.Join(c.dir, ref) }
-// cached opens ref's file if the cache holds it, waiting for a fill
-// already under way, and marks it the most recently served.
-func (c *clipCache) cached(ref string) (*os.File, string, bool) {
+// get is key's video as something ranges can be served from, its kind,
+// and what releases it. A completed entry is used as it is. Otherwise
+// one request fills it: load is called once (concurrent misses for the
+// same key wait on that fill, then use what it made), the bytes are
+// streamed into a file of their own, at most maxVideoBytes, and their
+// SHA-256 checked against key when verify (a registered clip's key is
+// its hash; a staged clip's is not). A reader from load that can seek
+// (blobs.Dir's file) is served from where it is and not cached.
+//
+// The lookup and the open happen together under mu, and eviction holds
+// mu too, so a file is never unlinked between them; one unlinked while
+// a response reads it stays readable to that response until it closes
+// (POSIX), and the file just renamed into place is never the one
+// eviction takes.
+func (c *clipCache) get(key string, verify bool, load func() (string, io.Reader, func(), error)) (io.ReadSeeker, string, func(), error) {
for {
c.mu.Lock()
- if el, ok := c.entries[ref]; ok {
- c.lru.MoveToFront(el)
+ if el, ok := c.entries[key]; ok {
e := el.Value.(*clipEntry)
- f, err := os.Open(c.path(ref))
- if err != nil {
- c.drop(el)
+ f, err := os.Open(c.path(key))
+ if err == nil {
+ c.lru.MoveToFront(el)
c.mu.Unlock()
- return nil, "", false
+ return f, e.kind, func() { f.Close() }, nil
}
+ // Gone from under us: forgotten, and filled again.
+ c.forget(el)
+ }
+ if wait, busy := c.filling[key]; busy {
c.mu.Unlock()
- return f, e.kind, true
+ <-wait
+ continue
}
- wait, filling := c.filling[ref]
+ done := make(chan struct{})
+ c.filling[key] = done
c.mu.Unlock()
- if !filling {
- return nil, "", false
- }
- <-wait
+ body, kind, release, err := c.fillFrom(key, verify, load)
+ c.mu.Lock()
+ delete(c.filling, key)
+ c.mu.Unlock()
+ close(done)
+ return body, kind, release, err
}
}
-// fill streams r, at most maxVideoBytes of it, into ref's file and
-// opens it. verify checks the bytes' SHA-256 is ref, which it is for
-// anything registered; a staged clip's key is not a hash of its bytes.
-// A fill already under way for ref is waited for instead.
-func (c *clipCache) fill(ref, kind string, r io.Reader, verify bool) (*os.File, error) {
- c.mu.Lock()
- if _, busy := c.filling[ref]; busy {
- c.mu.Unlock()
- if f, _, ok := c.cached(ref); ok {
- return f, nil
+// fillFrom is get's fill, run by the one request that claimed key.
+func (c *clipCache) fillFrom(key string, verify bool, load func() (string, io.Reader, func(), error)) (io.ReadSeeker, string, func(), error) {
+ kind, r, closeLoad, err := load()
+ if err != nil {
+ return nil, "", nil, err
+ }
+ if rs, ok := r.(io.ReadSeeker); ok {
+ if _, err := rs.Seek(0, io.SeekStart); err == nil {
+ return rs, kind, closeLoad, nil
}
- return nil, errClipChanged
}
- done := make(chan struct{})
- c.filling[ref] = done
- c.mu.Unlock()
- defer func() {
- c.mu.Lock()
- delete(c.filling, ref)
- c.mu.Unlock()
- close(done)
- }()
-
+ defer closeLoad()
if err := c.mkdir(); err != nil {
- return nil, err
+ return nil, "", nil, err
}
tmp, err := os.CreateTemp(c.dir, ".fill-*")
if err != nil {
- return nil, err
+ return nil, "", nil, err
}
defer os.Remove(tmp.Name())
sum := sha256.New()
@@ -145,36 +155,44 @@ func (c *clipCache) fill(ref, kind string, r io.Reader, verify bool) (*os.File,
}
switch {
case err != nil:
- return nil, err
+ return nil, "", nil, err
case n > maxVideoBytes:
- return nil, errAssetTooLarge
- case verify && hex.EncodeToString(sum.Sum(nil)) != ref:
- return nil, errClipChanged
- }
- if err := os.Rename(tmp.Name(), c.path(ref)); err != nil {
- return nil, err
+ return nil, "", nil, errAssetTooLarge
+ case verify && hex.EncodeToString(sum.Sum(nil)) != key:
+ return nil, "", nil, errClipChanged
}
c.mu.Lock()
- if el, ok := c.entries[ref]; ok {
- c.drop(el)
+ defer c.mu.Unlock()
+ if err := os.Rename(tmp.Name(), c.path(key)); err != nil {
+ return nil, "", nil, err
+ }
+ f, err := os.Open(c.path(key))
+ if err != nil {
+ return nil, "", nil, err
}
- c.entries[ref] = c.lru.PushFront(&clipEntry{ref: ref, kind: kind, size: n})
+ c.entries[key] = c.lru.PushFront(&clipEntry{ref: key, kind: kind, size: n})
c.total += n
for c.total > c.limit && c.lru.Len() > 1 {
c.drop(c.lru.Back())
}
- c.mu.Unlock()
- return os.Open(c.path(ref))
+ return f, kind, func() { f.Close() }, nil
}
-// drop forgets an entry and removes its file; a reader that has it open
-// keeps what it has. Called with mu held.
-func (c *clipCache) drop(el *list.Element) {
+// forget drops an entry whose file is already gone. Called with mu held.
+func (c *clipCache) forget(el *list.Element) {
e := el.Value.(*clipEntry)
c.lru.Remove(el)
delete(c.entries, e.ref)
c.total -= e.size
- os.Remove(c.path(e.ref))
+}
+
+// drop forgets an entry and unlinks its file; a response that has it
+// open reads on to the end. Called with mu held, never for the entry
+// just filled (it is at the front, and the list keeps at least one).
+func (c *clipCache) drop(el *list.Element) {
+ key := el.Value.(*clipEntry).ref
+ c.forget(el)
+ os.Remove(c.path(key))
}
// close removes the cache's directory if it made one.
diff --git a/internal/slides/clipcache_test.go b/internal/slides/clipcache_test.go
index 5e5664b..27400ba 100644
--- a/internal/slides/clipcache_test.go
+++ b/internal/slides/clipcache_test.go
@@ -8,7 +8,10 @@ import (
"io"
"os"
"strings"
+ "sync"
+ "sync/atomic"
"testing"
+ "time"
)
func refOf(b []byte) string {
@@ -16,64 +19,116 @@ func refOf(b []byte) string {
return hex.EncodeToString(s[:])
}
-// TestTheClipCacheKeepsTheLatestUnderItsCap: filled once per ref, read
-// back whole, the least recently served dropped past the cap, bytes that
-// are not their ref never kept, and the directory gone on close.
-func TestTheClipCacheKeepsTheLatestUnderItsCap(t *testing.T) {
- c := newClipCache("", 100)
- videos := [][]byte{bytes.Repeat([]byte("a"), 40), bytes.Repeat([]byte("b"), 40), bytes.Repeat([]byte("c"), 40)}
- for i, v := range videos[:2] {
- f, err := c.fill(refOf(v), "video/webm", bytes.NewReader(v), true)
- if err != nil {
- t.Fatalf("fill %d: %v", i, err)
+// reader is a load that cannot seek, counting how often it is asked.
+func reader(b []byte, loads *atomic.Int32) func() (string, io.Reader, func(), error) {
+ return func() (string, io.Reader, func(), error) {
+ loads.Add(1)
+ return "video/webm", io.NopCloser(bytes.NewReader(b)), func() {}, nil
+ }
+}
+
+func getAll(t *testing.T, c *clipCache, key string, verify bool, load func() (string, io.Reader, func(), error)) []byte {
+ t.Helper()
+ body, kind, done, err := c.get(key, verify, load)
+ if err != nil {
+ t.Fatalf("get %s: %v", key[:6], err)
+ }
+ defer done()
+ if kind != "video/webm" {
+ t.Errorf("kind %q", kind)
+ }
+ got, _ := io.ReadAll(body)
+ return got
+}
+
+// TestTheClipCacheFillsOnceAndReusesIt: one entry per key, filled by
+// one load whoever asks and however many at once; asked again, the
+// completed entry is used and nothing is loaded.
+func TestTheClipCacheFillsOnceAndReusesIt(t *testing.T) {
+ c := newClipCache("", 1<<20)
+ defer c.close()
+ v := bytes.Repeat([]byte("v"), 5000)
+ var loads atomic.Int32
+ slow := func() (string, io.Reader, func(), error) {
+ time.Sleep(50 * time.Millisecond)
+ return reader(v, &loads)()
+ }
+ var wg sync.WaitGroup
+ for i := 0; i < 8; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if got := getAll(t, c, refOf(v), true, slow); !bytes.Equal(got, v) {
+ t.Error("a waiter read the wrong bytes")
+ }
+ }()
+ }
+ wg.Wait()
+ for i := 0; i < 3; i++ {
+ if got := getAll(t, c, refOf(v), true, reader(v, &loads)); !bytes.Equal(got, v) {
+ t.Fatal("the cached entry is not the clip")
}
- got, _ := io.ReadAll(f)
- f.Close()
- if !bytes.Equal(got, v) {
- t.Fatalf("fill %d read back %q", i, got)
+ }
+ if n := loads.Load(); n != 1 {
+ t.Errorf("loaded %d times, want once", n)
+ }
+ // A staged key is not a hash of its bytes, and reused just the same.
+ var staged atomic.Int32
+ for i := 0; i < 2; i++ {
+ if got := getAll(t, c, "staged-abc", false, reader(v, &staged)); !bytes.Equal(got, v) {
+ t.Fatal("the staged entry is not the clip")
}
}
- // a is served again, so b is the least recently served.
- if f, kind, ok := c.cached(refOf(videos[0])); !ok || kind != "video/webm" {
- t.Fatal("a is not cached")
- } else {
- f.Close()
+ if n := staged.Load(); n != 1 {
+ t.Errorf("the staged clip loaded %d times, want once", n)
+ }
+ // Bytes that are not their ref are refused and never kept.
+ var wrong atomic.Int32
+ if _, _, _, err := c.get(strings.Repeat("ab", 32), true, reader(v, &wrong)); !errors.Is(err, errClipChanged) {
+ t.Errorf("the wrong bytes: %v", err)
+ }
+ if _, ok := c.entries[strings.Repeat("ab", 32)]; ok {
+ t.Error("the wrong bytes were kept")
}
- f, err := c.fill(refOf(videos[2]), "video/webm", bytes.NewReader(videos[2]), true)
+}
+
+// TestTheClipCacheEvictsWithoutBreakingWhatIsBeingServed: past the cap
+// the least recently served goes, and a response already reading it
+// reads it to the end.
+func TestTheClipCacheEvictsWithoutBreakingWhatIsBeingServed(t *testing.T) {
+ c := newClipCache("", 100)
+ var loads atomic.Int32
+ a, b, d := bytes.Repeat([]byte("a"), 40), bytes.Repeat([]byte("b"), 40), bytes.Repeat([]byte("d"), 40)
+ held, _, done, err := c.get(refOf(a), true, reader(a, &loads))
if err != nil {
t.Fatal(err)
}
- f.Close()
- if _, _, ok := c.cached(refOf(videos[1])); ok {
- t.Error("b was kept past the cap")
- }
- for _, v := range [][]byte{videos[0], videos[2]} {
- if f, _, ok := c.cached(refOf(v)); !ok {
- t.Errorf("%q was dropped", v[:1])
- } else {
- f.Close()
- }
+ first := make([]byte, 10)
+ if _, err := io.ReadFull(held, first); err != nil {
+ t.Fatal(err)
}
- if c.total != 80 {
- t.Errorf("the cache holds %d bytes, want 80", c.total)
+ getAll(t, c, refOf(b), true, reader(b, &loads))
+ getAll(t, c, refOf(d), true, reader(d, &loads)) // a is the least recently served: gone
+ if _, ok := c.entries[refOf(a)]; ok {
+ t.Error("a was kept past the cap")
}
- // Bytes that are not their ref are not kept; a staged key is not checked.
- if _, err := c.fill(strings.Repeat("ab", 32), "video/webm", bytes.NewReader(videos[1]), true); !errors.Is(err, errClipChanged) {
- t.Errorf("a fill under the wrong ref: %v", err)
+ rest, err := io.ReadAll(held)
+ done()
+ if err != nil || !bytes.Equal(append(first, rest...), a) {
+ t.Errorf("the response serving a read %q, %v", append(first, rest...), err)
}
- if _, _, ok := c.cached(strings.Repeat("ab", 32)); ok {
- t.Error("the wrong bytes were kept")
+ for _, v := range [][]byte{b, d} {
+ if got := getAll(t, c, refOf(v), true, reader(v, &loads)); !bytes.Equal(got, v) {
+ t.Errorf("%q was lost", v[:1])
+ }
}
- if f, err := c.fill("staged-x", "video/webm", bytes.NewReader(videos[1]), false); err != nil {
- t.Errorf("a staged fill: %v", err)
- } else {
- f.Close()
+ if loads.Load() != 3 || c.total != 80 {
+ t.Errorf("loads %d, total %d; want 3 and 80", loads.Load(), c.total)
}
dir := c.dir
c.close()
if _, err := os.Stat(dir); !os.IsNotExist(err) {
t.Errorf("the cache's directory outlived it: %v", err)
}
- // A cache that never filled made nothing, and closes cleanly.
newClipCache("", 100).close()
}
diff --git a/internal/slides/clips.go b/internal/slides/clips.go
index dee2d0d..aca57be 100644
--- a/internal/slides/clips.go
+++ b/internal/slides/clips.go
@@ -296,22 +296,57 @@ func (a *app) posterFor(ctx context.Context, store blobs.Store, d Deck, ref stri
return "", nil
}
-// cachedVideo is a clip's bytes as something ranges can be served from:
-// the store's own reader when it seeks (blobs.Dir's file), or else the
-// clip cache's file (clipcache.go), filled from it in one streamed read
-// (head being what was already read of rc to sniff it). done releases
-// what it opened.
-func cachedVideo(cache *clipCache, key, kind string, head []byte, rc io.Reader, verify bool) (io.ReadSeeker, func(), error) {
- if rs, ok := rc.(io.ReadSeeker); ok {
- if _, err := rs.Seek(0, io.SeekStart); err == nil {
- return rs, func() {}, nil
+// errNotVideo is an object that does not open as a clip's video does.
+var errNotVideo = errors.New("slides: this object is not a video")
+
+// videoLoad is the clip cache's load for object: the store read once,
+// its head sniffed (anything but an MP4 or WebM is errNotVideo), and the
+// whole of it handed on as one stream.
+func videoLoad(ctx context.Context, store blobs.Store, object string) func() (string, io.Reader, func(), error) {
+ return func() (string, io.Reader, func(), error) {
+ rc, err := store.Get(ctx, object)
+ if err != nil {
+ return "", nil, nil, err
}
+ return sniffedVideo(rc)
+ }
+}
+
+// sniffedVideo reads rc's head, and answers its kind and rc again,
+// whole: rc itself when it seeks, else the head and the rest.
+func sniffedVideo(rc io.ReadCloser) (string, io.Reader, func(), error) {
+ head := make([]byte, 1024)
+ n, err := io.ReadFull(rc, head)
+ if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) {
+ rc.Close()
+ return "", nil, nil, err
}
- f, err := cache.fill(key, kind, io.MultiReader(bytes.NewReader(head), rc), verify)
+ kind := sniffVideo(head[:n])
+ if kind == "" {
+ rc.Close()
+ return "", nil, nil, errNotVideo
+ }
+ release := func() { rc.Close() }
+ if rs, ok := rc.(io.ReadSeeker); ok {
+ return kind, rs, release, nil
+ }
+ return kind, io.MultiReader(bytes.NewReader(head[:n]), rc), release, nil
+}
+
+// serveCachedVideo serves ref's video from the clip cache, filled by
+// load when it is not there yet.
+func (a *app) serveCachedVideo(w http.ResponseWriter, r *http.Request, cache *clipCache, ref string, load func() (string, io.Reader, func(), error)) {
+ body, kind, done, err := cache.get(ref, true, load)
if err != nil {
- return nil, nil, err
+ if errors.Is(err, blobs.ErrNotFound) || errors.Is(err, errNotVideo) {
+ a.notFound(w, r)
+ return
+ }
+ a.fail(w, r, "serve a clip", err)
+ return
}
- return f, func() { f.Close() }, nil
+ defer done()
+ serveVideo(w, r, kind, body)
}
// serveVideo hands over a clip's bytes in whatever ranges were asked
@@ -353,35 +388,18 @@ func (a *app) stagedVideo(w http.ResponseWriter, r *http.Request) {
a.notFound(w, r)
return
}
- rc, err := store.Get(r.Context(), up.ObjectKey)
+ // A staging key names an upload, not its bytes: cached apart from
+ // any registered clip, unchecked against its name, and read from the
+ // store once however many ranges the poster's drawing asks for.
+ body, kind, done, err := a.clipCacheFor().get("staged-"+key, false, videoLoad(r.Context(), store, up.ObjectKey))
if err != nil {
- if errors.Is(err, blobs.ErrNotFound) {
+ if errors.Is(err, blobs.ErrNotFound) || errors.Is(err, errNotVideo) {
a.notFound(w, r)
return
}
a.fail(w, r, "read a staged clip", err)
return
}
- defer rc.Close()
- head := make([]byte, 1024)
- n, err := io.ReadFull(rc, head)
- if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) {
- a.fail(w, r, "read a staged clip", err)
- return
- }
- kind := sniffVideo(head[:n])
- if kind == "" {
- a.notFound(w, r)
- return
- }
- // A staging key names an upload, not its bytes: cached apart from
- // any registered clip, unchecked against its name.
- cache := a.clipCacheFor()
- body, done, err := cachedVideo(cache, "staged-"+key, kind, head[:n], rc, false)
- if err != nil {
- a.fail(w, r, "cache a staged clip", err)
- return
- }
defer done()
w.Header().Set("Cache-Control", "no-store")
serveVideo(w, r, kind, body)
diff --git a/internal/slidestest/clips_test.go b/internal/slidestest/clips_test.go
index 36ab5cf..20c53a1 100644
--- a/internal/slidestest/clips_test.go
+++ b/internal/slidestest/clips_test.go
@@ -21,6 +21,7 @@ import (
"strings"
"sync"
"testing"
+ "time"
"amadan.net/rastrillo/rastrillo/blobs"
@@ -387,9 +388,19 @@ type unseekableStore struct {
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
@@ -516,3 +527,78 @@ func TestAClipsDescriptionIsItsPosters(t *testing.T) {
}
}
}
+
+// 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)
+ }
+}