| 1 | // clipcache.go keeps clips' videos on this instance's disk while it |
| 2 | // serves them (scenes and clips spec §2; clips review, fix round 1). |
| 3 | // |
| 4 | // A browser plays a video in ranges: a request for the start, more as |
| 5 | // it plays, one for the end to learn the length, one per seek. A store |
| 6 | // whose reader can seek (blobs.Dir's file) answers each from where it |
| 7 | // is. One that cannot (the platform's bucket behind ThroughApp, a |
| 8 | // sealed store) would have to be read from the start for every range, |
| 9 | // and the whole of it held to answer one. So such a video is read from |
| 10 | // the store once, streamed into a file here named by its ref, its |
| 11 | // SHA-256 checked against that ref as it goes, and every range is |
| 12 | // served from the file with http.ServeContent. Nothing is ever held |
| 13 | // whole in memory. |
| 14 | // |
| 15 | // One entry per key: a clip's content hash, or a staged upload's |
| 16 | // staging key. Requests that miss together wait on one fill; a filled |
| 17 | // entry is used by everyone after. The cache is bounded: 1 GiB in all, |
| 18 | // the least recently served video dropped first. It is this process's alone and starts empty: a |
| 19 | // directory of its own under the system's temporary directory, removed |
| 20 | // when the app closes, unless Config.ClipCache names one to use. |
| 21 | package slides |
| 22 | |
| 23 | import ( |
| 24 | "container/list" |
| 25 | "crypto/sha256" |
| 26 | "encoding/hex" |
| 27 | "errors" |
| 28 | "fmt" |
| 29 | "io" |
| 30 | "os" |
| 31 | "path/filepath" |
| 32 | "sync" |
| 33 | ) |
| 34 | |
| 35 | // clipCacheLimit is the most the cache holds on disk. |
| 36 | const clipCacheLimit = 1 << 30 |
| 37 | |
| 38 | // errClipChanged is bytes from the store that are not the ref they were |
| 39 | // asked for under: never kept. |
| 40 | var errClipChanged = errors.New("slides: a clip's bytes do not have its ref's hash") |
| 41 | |
| 42 | type clipCache struct { |
| 43 | dir string |
| 44 | limit int64 |
| 45 | owned bool |
| 46 | // made makes dir on the first fill, so an app that never serves a |
| 47 | // clip from a store that cannot seek makes no directory. |
| 48 | made sync.Once |
| 49 | madeErr error |
| 50 | |
| 51 | mu sync.Mutex |
| 52 | entries map[string]*list.Element // ref → its place in lru |
| 53 | lru *list.List // *clipEntry, the most recently served at the front |
| 54 | total int64 |
| 55 | filling map[string]chan struct{} |
| 56 | } |
| 57 | |
| 58 | type clipEntry struct { |
| 59 | ref, kind string |
| 60 | size int64 |
| 61 | } |
| 62 | |
| 63 | // newClipCache is a cache in dir, or in a new directory of its own |
| 64 | // under the system's temporary directory when dir is empty. |
| 65 | func newClipCache(dir string, limit int64) *clipCache { |
| 66 | return &clipCache{dir: dir, limit: limit, owned: dir == "", entries: map[string]*list.Element{}, lru: list.New(), filling: map[string]chan struct{}{}} |
| 67 | } |
| 68 | |
| 69 | // mkdir makes the cache's directory, once. |
| 70 | func (c *clipCache) mkdir() error { |
| 71 | c.made.Do(func() { |
| 72 | if c.owned { |
| 73 | c.dir, c.madeErr = os.MkdirTemp("", "slides-clips-") |
| 74 | } else { |
| 75 | c.madeErr = os.MkdirAll(c.dir, 0o700) |
| 76 | } |
| 77 | if c.madeErr != nil { |
| 78 | c.madeErr = fmt.Errorf("slides: make the clip cache: %w", c.madeErr) |
| 79 | } |
| 80 | }) |
| 81 | return c.madeErr |
| 82 | } |
| 83 | |
| 84 | func (c *clipCache) path(ref string) string { return filepath.Join(c.dir, ref) } |
| 85 | |
| 86 | // get is key's video as something ranges can be served from, its kind, |
| 87 | // and what releases it. A completed entry is used as it is. Otherwise |
| 88 | // one request fills it: load is called once (concurrent misses for the |
| 89 | // same key wait on that fill, then use what it made), the bytes are |
| 90 | // streamed into a file of their own, at most maxVideoBytes, and their |
| 91 | // SHA-256 checked against key when verify (a registered clip's key is |
| 92 | // its hash; a staged clip's is not). A reader from load that can seek |
| 93 | // (blobs.Dir's file) is served from where it is and not cached. |
| 94 | // |
| 95 | // The lookup and the open happen together under mu, and eviction holds |
| 96 | // mu too, so a file is never unlinked between them; one unlinked while |
| 97 | // a response reads it stays readable to that response until it closes |
| 98 | // (POSIX), and the file just renamed into place is never the one |
| 99 | // eviction takes. |
| 100 | func (c *clipCache) get(key string, verify bool, load func() (string, io.Reader, func(), error)) (io.ReadSeeker, string, func(), error) { |
| 101 | for { |
| 102 | c.mu.Lock() |
| 103 | if el, ok := c.entries[key]; ok { |
| 104 | e := el.Value.(*clipEntry) |
| 105 | f, err := os.Open(c.path(key)) |
| 106 | if err == nil { |
| 107 | c.lru.MoveToFront(el) |
| 108 | c.mu.Unlock() |
| 109 | return f, e.kind, func() { f.Close() }, nil |
| 110 | } |
| 111 | // Gone from under us: forgotten, and filled again. |
| 112 | c.forget(el) |
| 113 | } |
| 114 | if wait, busy := c.filling[key]; busy { |
| 115 | c.mu.Unlock() |
| 116 | <-wait |
| 117 | continue |
| 118 | } |
| 119 | done := make(chan struct{}) |
| 120 | c.filling[key] = done |
| 121 | c.mu.Unlock() |
| 122 | body, kind, release, err := c.fillFrom(key, verify, load) |
| 123 | c.mu.Lock() |
| 124 | delete(c.filling, key) |
| 125 | c.mu.Unlock() |
| 126 | close(done) |
| 127 | return body, kind, release, err |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | // fillFrom is get's fill, run by the one request that claimed key. |
| 132 | func (c *clipCache) fillFrom(key string, verify bool, load func() (string, io.Reader, func(), error)) (io.ReadSeeker, string, func(), error) { |
| 133 | kind, r, closeLoad, err := load() |
| 134 | if err != nil { |
| 135 | return nil, "", nil, err |
| 136 | } |
| 137 | if rs, ok := r.(io.ReadSeeker); ok { |
| 138 | if _, err := rs.Seek(0, io.SeekStart); err == nil { |
| 139 | return rs, kind, closeLoad, nil |
| 140 | } |
| 141 | } |
| 142 | defer closeLoad() |
| 143 | if err := c.mkdir(); err != nil { |
| 144 | return nil, "", nil, err |
| 145 | } |
| 146 | tmp, err := os.CreateTemp(c.dir, ".fill-*") |
| 147 | if err != nil { |
| 148 | return nil, "", nil, err |
| 149 | } |
| 150 | defer os.Remove(tmp.Name()) |
| 151 | sum := sha256.New() |
| 152 | n, err := io.Copy(io.MultiWriter(tmp, sum), io.LimitReader(r, maxVideoBytes+1)) |
| 153 | if cerr := tmp.Close(); err == nil { |
| 154 | err = cerr |
| 155 | } |
| 156 | switch { |
| 157 | case err != nil: |
| 158 | return nil, "", nil, err |
| 159 | case n > maxVideoBytes: |
| 160 | return nil, "", nil, errAssetTooLarge |
| 161 | case verify && hex.EncodeToString(sum.Sum(nil)) != key: |
| 162 | return nil, "", nil, errClipChanged |
| 163 | } |
| 164 | c.mu.Lock() |
| 165 | defer c.mu.Unlock() |
| 166 | if err := os.Rename(tmp.Name(), c.path(key)); err != nil { |
| 167 | return nil, "", nil, err |
| 168 | } |
| 169 | f, err := os.Open(c.path(key)) |
| 170 | if err != nil { |
| 171 | return nil, "", nil, err |
| 172 | } |
| 173 | c.entries[key] = c.lru.PushFront(&clipEntry{ref: key, kind: kind, size: n}) |
| 174 | c.total += n |
| 175 | for c.total > c.limit && c.lru.Len() > 1 { |
| 176 | c.drop(c.lru.Back()) |
| 177 | } |
| 178 | return f, kind, func() { f.Close() }, nil |
| 179 | } |
| 180 | |
| 181 | // forget drops an entry whose file is already gone. Called with mu held. |
| 182 | func (c *clipCache) forget(el *list.Element) { |
| 183 | e := el.Value.(*clipEntry) |
| 184 | c.lru.Remove(el) |
| 185 | delete(c.entries, e.ref) |
| 186 | c.total -= e.size |
| 187 | } |
| 188 | |
| 189 | // drop forgets an entry and unlinks its file; a response that has it |
| 190 | // open reads on to the end. Called with mu held, never for the entry |
| 191 | // just filled (it is at the front, and the list keeps at least one). |
| 192 | func (c *clipCache) drop(el *list.Element) { |
| 193 | key := el.Value.(*clipEntry).ref |
| 194 | c.forget(el) |
| 195 | os.Remove(c.path(key)) |
| 196 | } |
| 197 | |
| 198 | // close removes the cache's directory if it made one. |
| 199 | func (c *clipCache) close() { |
| 200 | if c == nil || !c.owned { |
| 201 | return |
| 202 | } |
| 203 | c.made.Do(func() { c.madeErr = errors.New("slides: the clip cache is closed") }) |
| 204 | if c.madeErr == nil && c.dir != "" { |
| 205 | os.RemoveAll(c.dir) |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | // clipCacheFor is the app's cache, made on first use. |
| 210 | func (a *app) clipCacheFor() *clipCache { |
| 211 | a.clipOnce.Do(func() { a.clips = newClipCache(a.cfg.ClipCache, clipCacheLimit) }) |
| 212 | return a.clips |
| 213 | } |
| 214 | |