assetcache: Commit, Get, leased Readers and expiry
Commit writes the gzip copy, draws a fresh version, encodes the final meta (ErrTooLarge past MaxMeta, before any rename), fsyncs and renames the versioned bodies, then renames the meta over <id>.meta under a per-id lock, swaps the index slot and releases the reservation. The previous version is retired: unlinked at once, its bytes counted (and reported as Stats.Retired) until the last Reader closes. Get deletes expired entries through drop, the one retire path eviction, Retain and the sweep will use. The store now counts .meta bytes with the bodies, at Open as well as at Commit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+1,242
−46
internal/assetcache/entry_test.go+633 −0internal/assetcache/fill.go+301 −18internal/assetcache/meta.go+10 −0internal/assetcache/store.go+279 −21internal/assetcache/store_test.go+19 −7
diff --git a/internal/assetcache/entry_test.go b/internal/assetcache/entry_test.go| new file mode 100644 |
| index 000000000..84ae6b723 |
| --- /dev/null |
| +++ b/internal/assetcache/entry_test.go |
| @@ -0,0 +1,633 @@ |
| +package assetcache |
| + |
| +import ( |
| + "bytes" |
| + "compress/gzip" |
| + "crypto/rand" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// clock is a settable Now for tests. |
| +type clock struct { |
| + mu sync.Mutex |
| + now time.Time |
| +} |
| + |
| +func (c *clock) Now() time.Time { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.now |
| +} |
| + |
| +func (c *clock) set(t time.Time) { |
| + c.mu.Lock() |
| + c.now = t |
| + c.mu.Unlock() |
| +} |
| + |
| +// entryStore opens a Store over a real temporary directory with a fake FS |
| +// that has plenty of room, the given budget and a settable clock. |
| +func entryStore(t *testing.T, budget int64) (*Store, *clock, string) { |
| + t.Helper() |
| + dir := t.TempDir() |
| + c := &clock{now: testNow} |
| + s, err := Open(Config{Dir: dir, Budget: budget, FS: &fakeFS{total: 64 << 30, free: 64 << 30}, Now: c.Now}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s, c, dir |
| +} |
| + |
| +// reopen opens a second Store over dir, as a restarted process would. |
| +func reopen(t *testing.T, dir string) *Store { |
| + t.Helper() |
| + s, err := Open(Config{Dir: dir, Budget: 4 << 30, FS: &fakeFS{total: 64 << 30, free: 64 << 30}, Now: func() time.Time { return testNow }}) |
| + if err != nil { |
| + t.Fatalf("Open: %v", err) |
| + } |
| + return s |
| +} |
| + |
| +func cssHeader(v string) http.Header { |
| + return http.Header{"Content-Type": {"text/css"}, "X-Version": {v}} |
| +} |
| + |
| +// fill reserves for k, writes body and returns the open fill. |
| +func fill(t *testing.T, s *Store, k Key, body []byte) *Fill { |
| + t.Helper() |
| + f, err := s.Reserve(k, int64(len(body))) |
| + if err != nil { |
| + t.Fatalf("Reserve: %v", err) |
| + } |
| + if _, err := f.Write(body); err != nil { |
| + t.Fatalf("Write: %v", err) |
| + } |
| + return f |
| +} |
| + |
| +// commit stores body under k with header h, valid for an hour from testNow. |
| +func commit(t *testing.T, s *Store, k Key, body []byte, h http.Header, gz bool) { |
| + t.Helper() |
| + f := fill(t, s, k, body) |
| + if err := f.Commit(Meta{Header: h, Lifetime: time.Hour, Expires: testNow.Add(time.Hour)}, gz); err != nil { |
| + t.Fatalf("Commit: %v", err) |
| + } |
| +} |
| + |
| +func mustGet(t *testing.T, s *Store, k Key) *Entry { |
| + t.Helper() |
| + e, ok := s.Get(k) |
| + if !ok { |
| + t.Fatalf("Get(%s): no entry", k.Path) |
| + } |
| + return e |
| +} |
| + |
| +func readAll(t *testing.T, e *Entry, gz bool) []byte { |
| + t.Helper() |
| + r, err := e.Open(gz) |
| + if err != nil { |
| + t.Fatalf("Open(gzip=%v): %v", gz, err) |
| + } |
| + defer r.Close() |
| + b, err := io.ReadAll(r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b |
| +} |
| + |
| +func gunzip(t *testing.T, b []byte) []byte { |
| + t.Helper() |
| + zr, err := gzip.NewReader(bytes.NewReader(b)) |
| + if err != nil { |
| + t.Fatalf("gzip.NewReader: %v", err) |
| + } |
| + out, err := io.ReadAll(zr) |
| + if err != nil { |
| + t.Fatalf("gunzip: %v", err) |
| + } |
| + return out |
| +} |
| + |
| +func fileSize(t *testing.T, path string) int64 { |
| + t.Helper() |
| + fi, err := os.Stat(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return fi.Size() |
| +} |
| + |
| +func slots(s *Store) (box, apps int) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.fills, len(s.fillsByApp) |
| +} |
| + |
| +var cssText = []byte(strings.Repeat("body { margin: 0; padding: 0; color: #222; }\n", 200)) |
| + |
| +// TestCommitThenGetRoundTrips is not acceptance: it uses a fake FS. |
| +func TestCommitThenGetRoundTrips(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + f := fill(t, s, k, cssText) |
| + if err := f.Commit(Meta{Header: cssHeader("1"), Lifetime: time.Hour, Expires: testNow.Add(time.Hour)}, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.Abort() // after Commit: a no-op |
| + |
| + e := mustGet(t, s, k) |
| + if got := e.Meta.Header; got.Get("Content-Type") != "text/css" || got.Get("X-Version") != "1" { |
| + t.Fatalf("Header = %v", got) |
| + } |
| + if e.Meta.Key != k || e.Meta.Size != int64(len(cssText)) || e.Meta.GzipSize != 0 || !e.Meta.StoredAt.Equal(testNow) || !validVersion(e.Meta.Version) { |
| + t.Fatalf("Meta = %+v", e.Meta) |
| + } |
| + if got := readAll(t, e, false); !bytes.Equal(got, cssText) { |
| + t.Fatalf("body = %d bytes, want %d", len(got), len(cssText)) |
| + } |
| + if _, err := e.Open(true); err == nil { |
| + t.Fatal("Open(gzip) succeeded with no gzip copy") |
| + } |
| + |
| + metaSize := fileSize(t, filepath.Join(dir, k.ID()+".meta")) |
| + want := Stats{Entries: 1, Bytes: int64(len(cssText)) + metaSize, Apps: 1} |
| + if st := s.Stats(); st != want { |
| + t.Fatalf("Stats = %+v, want %+v", st, want) |
| + } |
| + if box, apps := slots(s); box != 0 || apps != 0 { |
| + t.Fatalf("slots after Commit: box %d, apps %d", box, apps) |
| + } |
| + sameNames(t, listDir(t, dir), []string{k.ID() + ".meta", bodyName(k.ID(), e.Meta.Version)}) |
| + if err := f.Commit(Meta{}, false); err == nil { |
| + t.Fatal("a second Commit succeeded") |
| + } |
| +} |
| + |
| +// TestReaderServesHTTP is not acceptance: it uses a fake FS. The Reader is |
| +// what http.ServeContent takes: a ranged request reads through Seek. |
| +func TestReaderServesHTTP(t *testing.T) { |
| + s, _, _ := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + commit(t, s, k, cssText, cssHeader("1"), false) |
| + r, err := mustGet(t, s, k).Open(false) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer r.Close() |
| + var _ io.ReadSeeker = r |
| + var _ io.ReaderAt = r |
| + fi, err := r.Stat() |
| + if err != nil || fi.Size() != int64(len(cssText)) { |
| + t.Fatalf("Stat = %v, %v", fi, err) |
| + } |
| + buf := make([]byte, 4) |
| + if _, err := r.ReadAt(buf, 5); err != nil || string(buf) != string(cssText[5:9]) { |
| + t.Fatalf("ReadAt = %q, %v", buf, err) |
| + } |
| + if _, err := r.Seek(7, io.SeekStart); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := io.ReadFull(r, buf); err != nil || string(buf) != string(cssText[7:11]) { |
| + t.Fatalf("Read after Seek = %q, %v", buf, err) |
| + } |
| + if err := r.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.Close() // a second Close releases nothing more |
| + s.mu.Lock() |
| + leases := s.entries[k.ID()].ver.leases |
| + s.mu.Unlock() |
| + if leases != 0 { |
| + t.Fatalf("leases = %d after Close twice, want 0", leases) |
| + } |
| +} |
| + |
| +// TestCommitThenReopenThenRead is not acceptance: it uses a fake FS. |
| +func TestCommitThenReopenThenRead(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + commit(t, s, k, cssText, cssHeader("1"), true) |
| + committed := mustGet(t, s, k).Meta |
| + |
| + s2 := reopen(t, dir) |
| + e := mustGet(t, s2, k) |
| + if e.Meta.Version != committed.Version { |
| + t.Fatalf("Version after reopen = %q, want %q", e.Meta.Version, committed.Version) |
| + } |
| + if e.Meta.GzipSize == 0 || e.Meta.GzipSize != committed.GzipSize || e.Meta.Header.Get("X-Version") != "1" { |
| + t.Fatalf("Meta after reopen = %+v", e.Meta) |
| + } |
| + if got := readAll(t, e, false); !bytes.Equal(got, cssText) { |
| + t.Fatal("identity body differs after reopen") |
| + } |
| + if got := gunzip(t, readAll(t, e, true)); !bytes.Equal(got, cssText) { |
| + t.Fatal("gzip copy does not decode to the identity body after reopen") |
| + } |
| + if st, st2 := s.Stats(), s2.Stats(); st != st2 { |
| + t.Fatalf("Stats after reopen = %+v, before %+v", st2, st) |
| + } |
| +} |
| + |
| +// TestCommitWritesMetaLast is not acceptance: it uses a fake FS. A crash |
| +// after the bodies are renamed but before the meta rename leaves no entry. |
| +func TestCommitWritesMetaLast(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + f := fill(t, s, k, cssText) |
| + f.crashAt = crashBeforeMetaRename |
| + if err := f.Commit(Meta{Header: cssHeader("1"), Lifetime: time.Hour, Expires: testNow.Add(time.Hour)}, true); !errors.Is(err, errSimulatedCrash) { |
| + t.Fatalf("Commit = %v, want the simulated crash", err) |
| + } |
| + var bodies int |
| + for _, name := range listDir(t, dir) { |
| + if name == k.ID()+".meta" { |
| + t.Fatalf("<id>.meta exists before the meta rename: %v", listDir(t, dir)) |
| + } |
| + if strings.HasSuffix(name, ".body") || strings.HasSuffix(name, ".gz") { |
| + bodies++ |
| + } |
| + } |
| + if bodies != 2 { |
| + t.Fatalf("files at the crash: %v, want both versioned bodies renamed", listDir(t, dir)) |
| + } |
| + |
| + s2 := reopen(t, dir) |
| + if _, ok := s2.Get(k); ok { |
| + t.Fatal("an entry survived a crash before its meta rename") |
| + } |
| + sameNames(t, listDir(t, dir), nil) |
| +} |
| + |
| +// TestReplacementCrashKeepsTheOldEntry is not acceptance: it uses a fake FS. |
| +func TestReplacementCrashKeepsTheOldEntry(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + commit(t, s, k, []byte("old bytes"), cssHeader("old"), false) |
| + old := mustGet(t, s, k).Meta |
| + oldFiles := listDir(t, dir) |
| + |
| + f := fill(t, s, k, cssText) |
| + f.crashAt = crashBeforeMetaRename |
| + if err := f.Commit(Meta{Header: cssHeader("new"), Lifetime: time.Hour, Expires: testNow.Add(time.Hour)}, true); !errors.Is(err, errSimulatedCrash) { |
| + t.Fatalf("Commit = %v, want the simulated crash", err) |
| + } |
| + |
| + s2 := reopen(t, dir) |
| + e := mustGet(t, s2, k) |
| + if e.Meta.Version != old.Version || e.Meta.Header.Get("X-Version") != "old" { |
| + t.Fatalf("Meta after the crash = %+v, want the old entry", e.Meta) |
| + } |
| + if got := readAll(t, e, false); string(got) != "old bytes" { |
| + t.Fatalf("body after the crash = %q, want the old bytes", got) |
| + } |
| + sameNames(t, listDir(t, dir), oldFiles) |
| +} |
| + |
| +// TestOversizedMetaIsRefused is not acceptance: it uses a fake FS. |
| +func TestOversizedMetaIsRefused(t *testing.T) { |
| + big := strings.Repeat("x", 70<<10) |
| + for _, tc := range []struct { |
| + name string |
| + key Key |
| + hdr http.Header |
| + }{ |
| + {"header", testKey("shop", "/a.css"), http.Header{"X-Big": {big}}}, |
| + {"query", Key{Account: "abc", App: "shop", Gen: "g1", Host: "shop.example.com", Path: "/a.css", RawQuery: "q=" + big}, cssHeader("1")}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + f := fill(t, s, tc.key, cssText) |
| + err := f.Commit(Meta{Header: tc.hdr, Lifetime: time.Hour, Expires: testNow.Add(time.Hour)}, true) |
| + if !errors.Is(err, ErrTooLarge) { |
| + t.Fatalf("Commit = %v, want ErrTooLarge", err) |
| + } |
| + f.Abort() |
| + if got := listDir(t, dir); len(got) != 0 { |
| + t.Fatalf("files left: %v", got) |
| + } |
| + if st := s.Stats(); st != (Stats{}) { |
| + t.Fatalf("Stats = %+v, want nothing stored or reserved", st) |
| + } |
| + if box, apps := slots(s); box != 0 || apps != 0 { |
| + t.Fatalf("slots: box %d, apps %d", box, apps) |
| + } |
| + if _, ok := s.Get(tc.key); ok { |
| + t.Fatal("refused entry is indexed") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestCommitOfAFailedFillAborts is not acceptance: it uses a fake FS. |
| +func TestCommitOfAFailedFillAborts(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + f, err := s.Reserve(k, 4) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.Write([]byte("too long")); !errors.Is(err, ErrTooLarge) { |
| + t.Fatalf("Write = %v", err) |
| + } |
| + if err := f.Commit(Meta{Expires: testNow.Add(time.Hour)}, false); !errors.Is(err, ErrTooLarge) { |
| + t.Fatalf("Commit = %v, want ErrTooLarge", err) |
| + } |
| + if st := s.Stats(); st != (Stats{}) { |
| + t.Fatalf("Stats = %+v", st) |
| + } |
| + if got := listDir(t, dir); len(got) != 0 { |
| + t.Fatalf("files left: %v", got) |
| + } |
| +} |
| + |
| +// heldBytesRefuse checks that, with a reader holding retired bytes, a fill |
| +// that fits only by counting them as free is refused, and that it is admitted |
| +// once the reader closes. |
| +func heldBytesRefuse(t *testing.T, s *Store, held int64, r *Reader, wantBody []byte) { |
| + t.Helper() |
| + st := s.Stats() |
| + if st.Retired != held { |
| + t.Fatalf("Retired = %d, want %d", st.Retired, held) |
| + } |
| + // The smallest fill that does not fit while the held bytes are counted. |
| + n := (s.cfg.Budget-st.Bytes-st.Reserved-metaReserve)/2 + 1 |
| + if n < 0 || 2*n+metaReserve > s.cfg.Budget-(st.Bytes-held)-st.Reserved { |
| + t.Fatalf("test budget leaves no room for the probe: Stats %+v", st) |
| + } |
| + probe := testKey("blog", "/probe") |
| + if _, err := s.Reserve(probe, n); !errors.Is(err, ErrNoRoom) { |
| + t.Fatalf("Reserve(%d) with %d bytes held = %v, want ErrNoRoom", n, held, err) |
| + } |
| + // The reader still reads the unlinked bytes. |
| + got, err := io.ReadAll(r) |
| + if err != nil || !bytes.Equal(got, wantBody) { |
| + t.Fatalf("held reader read %d bytes, %v", len(got), err) |
| + } |
| + if err := r.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st2 := s.Stats(); st2.Retired != 0 || st2.Bytes != st.Bytes-held { |
| + t.Fatalf("Stats after Close = %+v, want Retired 0 and Bytes %d", st2, st.Bytes-held) |
| + } |
| + f, err := s.Reserve(probe, n) |
| + if err != nil { |
| + t.Fatalf("Reserve(%d) after the reader closed: %v", n, err) |
| + } |
| + f.Abort() |
| +} |
| + |
| +// TestEvictedBodyStaysCountedWhileAReaderHoldsIt is not acceptance: it uses a |
| +// fake FS. Eviction itself is Task 5; this drives drop, the function eviction |
| +// calls. |
| +func TestEvictedBodyStaysCountedWhileAReaderHoldsIt(t *testing.T) { |
| + s, _, dir := entryStore(t, 70000) |
| + k := testKey("shop", "/a.css") |
| + body := cssText[:1000] |
| + commit(t, s, k, body, cssHeader("1"), false) |
| + e := mustGet(t, s, k) |
| + r, err := e.Open(false) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.mu.Lock() |
| + ie := s.entries[k.ID()] |
| + s.mu.Unlock() |
| + if !s.drop(ie) { |
| + t.Fatal("drop refused the current entry") |
| + } |
| + if got := listDir(t, dir); len(got) != 0 { |
| + t.Fatalf("files after eviction: %v, want all unlinked at once", got) |
| + } |
| + if st := s.Stats(); st.Entries != 0 || st.Bytes != int64(len(body)) { |
| + t.Fatalf("Stats = %+v, want no entries and the held body counted", st) |
| + } |
| + if _, err := e.Open(false); err == nil { |
| + t.Fatal("Open of an evicted entry succeeded") |
| + } |
| + heldBytesRefuse(t, s, int64(len(body)), r, body) |
| +} |
| + |
| +// TestReplacedBodyStaysCountedWhileAReaderHoldsIt is not acceptance: it uses a |
| +// fake FS. |
| +func TestReplacedBodyStaysCountedWhileAReaderHoldsIt(t *testing.T) { |
| + s, _, dir := entryStore(t, 70000) |
| + k := testKey("shop", "/a.css") |
| + old := cssText[:1000] |
| + commit(t, s, k, old, cssHeader("old"), false) |
| + oldEntry := mustGet(t, s, k) |
| + r, err := oldEntry.Open(false) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + commit(t, s, k, []byte("new"), cssHeader("new"), false) |
| + e := mustGet(t, s, k) |
| + if got := readAll(t, e, false); string(got) != "new" { |
| + t.Fatalf("Get after replacement = %q", got) |
| + } |
| + sameNames(t, listDir(t, dir), []string{k.ID() + ".meta", bodyName(k.ID(), e.Meta.Version)}) |
| + metaSize := fileSize(t, filepath.Join(dir, k.ID()+".meta")) |
| + if st := s.Stats(); st.Entries != 1 || st.Bytes != int64(len(old))+3+metaSize { |
| + t.Fatalf("Stats = %+v, want the new entry and the held old body", st) |
| + } |
| + heldBytesRefuse(t, s, int64(len(old)), r, old) |
| +} |
| + |
| +// TestGzipCopyIsAbandonedWhenLarger is not acceptance: it uses a fake FS. |
| +func TestGzipCopyIsAbandonedWhenLarger(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + k := testKey("shop", "/noise.bin") |
| + body := make([]byte, 4096) |
| + if _, err := rand.Read(body); err != nil { |
| + t.Fatal(err) |
| + } |
| + commit(t, s, k, body, cssHeader("1"), true) |
| + e := mustGet(t, s, k) |
| + if e.Meta.GzipSize != 0 { |
| + t.Fatalf("GzipSize = %d, want the copy abandoned", e.Meta.GzipSize) |
| + } |
| + if _, err := e.Open(true); err == nil { |
| + t.Fatal("Open(gzip) succeeded with the copy abandoned") |
| + } |
| + sameNames(t, listDir(t, dir), []string{k.ID() + ".meta", bodyName(k.ID(), e.Meta.Version)}) |
| + if st := s.Stats(); st.Reserved != 0 { |
| + t.Fatalf("Reserved = %d", st.Reserved) |
| + } |
| +} |
| + |
| +// TestGzipCopyIsKept is not acceptance: it uses a fake FS. |
| +func TestGzipCopyIsKept(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + commit(t, s, k, cssText, cssHeader("1"), true) |
| + e := mustGet(t, s, k) |
| + if e.Meta.GzipSize <= 0 || e.Meta.GzipSize >= e.Meta.Size { |
| + t.Fatalf("GzipSize = %d for %d bytes of CSS", e.Meta.GzipSize, e.Meta.Size) |
| + } |
| + if got := fileSize(t, filepath.Join(dir, gzipName(k.ID(), e.Meta.Version))); got != e.Meta.GzipSize { |
| + t.Fatalf(".gz is %d bytes, meta says %d", got, e.Meta.GzipSize) |
| + } |
| + if got := gunzip(t, readAll(t, e, true)); !bytes.Equal(got, cssText) { |
| + t.Fatal("gzip copy does not decode to the identity body") |
| + } |
| + metaSize := fileSize(t, filepath.Join(dir, k.ID()+".meta")) |
| + if st := s.Stats(); st.Bytes != e.Meta.Size+e.Meta.GzipSize+metaSize { |
| + t.Fatalf("Bytes = %d, want both bodies and the meta", st.Bytes) |
| + } |
| +} |
| + |
| +// TestGetExpires is not acceptance: it uses a fake FS. |
| +func TestGetExpires(t *testing.T) { |
| + s, c, dir := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + commit(t, s, k, cssText, cssHeader("1"), true) |
| + |
| + c.set(testNow.Add(time.Hour - time.Nanosecond)) |
| + if _, ok := s.Get(k); !ok { |
| + t.Fatal("entry gone before it expires") |
| + } |
| + c.set(testNow.Add(time.Hour)) // exactly Expires |
| + if _, ok := s.Get(k); ok { |
| + t.Fatal("Get returned an entry at its expiry") |
| + } |
| + if got := listDir(t, dir); len(got) != 0 { |
| + t.Fatalf("files after expiry: %v", got) |
| + } |
| + if st := s.Stats(); st != (Stats{}) { |
| + t.Fatalf("Stats after expiry = %+v", st) |
| + } |
| +} |
| + |
| +// TestCommitReplacesAnEntry is not acceptance: it uses a fake FS. |
| +func TestCommitReplacesAnEntry(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + commit(t, s, k, cssText, cssHeader("old"), true) |
| + old := mustGet(t, s, k).Meta |
| + commit(t, s, k, []byte("new body"), cssHeader("new"), false) |
| + |
| + e := mustGet(t, s, k) |
| + if e.Meta.Version == old.Version || e.Meta.Header.Get("X-Version") != "new" || e.Meta.GzipSize != 0 { |
| + t.Fatalf("Meta = %+v, want the replacement", e.Meta) |
| + } |
| + if got := readAll(t, e, false); string(got) != "new body" { |
| + t.Fatalf("body = %q", got) |
| + } |
| + sameNames(t, listDir(t, dir), []string{k.ID() + ".meta", bodyName(k.ID(), e.Meta.Version)}) |
| + metaSize := fileSize(t, filepath.Join(dir, k.ID()+".meta")) |
| + want := Stats{Entries: 1, Bytes: int64(len("new body")) + metaSize, Apps: 1} |
| + if st := s.Stats(); st != want { |
| + t.Fatalf("Stats = %+v, want %+v", st, want) |
| + } |
| +} |
| + |
| +// TestAgeNeverNegative is not acceptance: it uses a fake FS. An entry stored |
| +// "in the future" after the clock steps back stays valid until its stored |
| +// expiry and reports age zero. |
| +func TestAgeNeverNegative(t *testing.T) { |
| + m := Meta{Lifetime: time.Hour, Expires: testNow.Add(time.Hour)} |
| + for _, tc := range []struct { |
| + now time.Time |
| + want time.Duration |
| + }{ |
| + {testNow, 0}, |
| + {testNow.Add(10 * time.Minute), 10 * time.Minute}, |
| + {testNow.Add(-5 * time.Minute), 0}, |
| + {testNow.Add(-48 * time.Hour), 0}, |
| + } { |
| + if got := m.Age(tc.now); got != tc.want { |
| + t.Errorf("Age(%v) = %v, want %v", tc.now, got, tc.want) |
| + } |
| + } |
| + |
| + s, c, _ := entryStore(t, 4<<30) |
| + k := testKey("shop", "/a.css") |
| + commit(t, s, k, cssText, cssHeader("1"), false) |
| + c.set(testNow.Add(-2 * time.Hour)) // the clock steps back |
| + e, ok := s.Get(k) |
| + if !ok { |
| + t.Fatal("entry gone after the clock stepped back") |
| + } |
| + if got := e.Meta.Age(c.Now()); got != 0 { |
| + t.Fatalf("Age = %v, want 0", got) |
| + } |
| +} |
| + |
| +// TestCommitGetAndReadConcurrently is not acceptance: it uses a fake FS. Run |
| +// with -race: replacements, reads and expiry of the same keys interleave, and |
| +// every counter comes back to what the directory holds. |
| +func TestCommitGetAndReadConcurrently(t *testing.T) { |
| + s, _, dir := entryStore(t, 4<<30) |
| + keys := []Key{testKey("shop", "/a.css"), testKey("blog", "/b.css")} |
| + var wg sync.WaitGroup |
| + for g := 0; g < 6; g++ { |
| + wg.Add(1) |
| + go func(g int) { |
| + defer wg.Done() |
| + for i := 0; i < 30; i++ { |
| + k := keys[(g+i)%2] |
| + switch g % 3 { |
| + case 0: |
| + body := []byte(fmt.Sprintf("%s %d %d", cssText[:200], g, i)) |
| + f, err := s.Reserve(k, int64(len(body))) |
| + if errors.Is(err, ErrBusy) { |
| + continue |
| + } |
| + if err != nil { |
| + t.Errorf("Reserve: %v", err) |
| + return |
| + } |
| + if _, err := f.Write(body); err != nil { |
| + t.Errorf("Write: %v", err) |
| + } |
| + if err := f.Commit(Meta{Lifetime: time.Hour, Expires: testNow.Add(time.Hour)}, i%2 == 0); err != nil { |
| + t.Errorf("Commit: %v", err) |
| + } |
| + case 1: |
| + if e, ok := s.Get(k); ok { |
| + if r, err := e.Open(false); err == nil { |
| + io.Copy(io.Discard, r) |
| + r.Close() |
| + } |
| + } |
| + case 2: |
| + s.mu.Lock() |
| + e := s.entries[k.ID()] |
| + s.mu.Unlock() |
| + if e != nil { |
| + s.drop(e) |
| + } |
| + } |
| + } |
| + }(g) |
| + } |
| + wg.Wait() |
| + |
| + st := s.Stats() |
| + if st.Reserved != 0 || st.Retired != 0 { |
| + t.Fatalf("Stats = %+v, want nothing reserved or retired", st) |
| + } |
| + var onDisk int64 |
| + for _, name := range listDir(t, dir) { |
| + if strings.Contains(name, ".tmp-") { |
| + t.Fatalf("temporary left: %s", name) |
| + } |
| + onDisk += fileSize(t, filepath.Join(dir, name)) |
| + } |
| + if st.Bytes != onDisk { |
| + t.Fatalf("Bytes = %d, directory holds %d", st.Bytes, onDisk) |
| + } |
| + if st2 := reopen(t, dir).Stats(); st2.Entries != st.Entries || st2.Bytes != st.Bytes { |
| + t.Fatalf("Stats after reopen = %+v, before %+v", st2, st) |
| + } |
| +} |
diff --git a/internal/assetcache/fill.go b/internal/assetcache/fill.go| index c2afff79a..b2b33e474 100644 |
| --- a/internal/assetcache/fill.go |
| +++ b/internal/assetcache/fill.go |
| @@ -1,12 +1,15 @@ |
| package assetcache |
| import ( |
| + "compress/gzip" |
| "crypto/rand" |
| "encoding/hex" |
| "errors" |
| "fmt" |
| + "io" |
| "os" |
| "path/filepath" |
| + "runtime" |
| "sync" |
| ) |
| @@ -17,6 +20,9 @@ const ( |
| // metaReserve is the disk a reservation sets aside for the .meta file. |
| metaReserve = 64 << 10 |
| + // MaxMeta is the largest encoded .meta file Commit writes. |
| + MaxMeta = metaReserve |
| + |
| // maxFillsPerBox and maxFillsPerApp bound the fills in flight. |
| maxFillsPerBox = 16 |
| maxFillsPerApp = 4 |
| @@ -58,15 +64,19 @@ type Fill struct { |
| id string |
| res reservation |
| - mu sync.Mutex |
| - tmp *os.File // identity body temporary |
| - tmpName string |
| - token string // names every temporary of this fill |
| - written int64 |
| - failed error // set by the first failed write |
| - done bool // committed or aborted: the fill slot is released |
| - held int64 // bytes of the reservation still counted in s.reserved |
| - left []leftover // temporaries an Abort could not remove yet |
| + mu sync.Mutex |
| + tmp *os.File // identity body temporary |
| + gz *os.File // gzip copy temporary, while Commit writes it |
| + bodyPath string // where the identity body is: its temporary, then its versioned name |
| + gzPath string // likewise for the gzip copy |
| + token string // names every temporary of this fill |
| + written int64 |
| + failed error // set by the first failed write |
| + done bool // committed or aborted: the fill slot is released |
| + held int64 // bytes of the reservation still counted in s.reserved |
| + left []leftover // temporaries an Abort could not remove yet |
| + |
| + crashAt string // tests only: the Commit stage at which to stop as a crash would |
| } |
| // leftover is a temporary still on disk and the bytes it holds. |
| @@ -159,8 +169,10 @@ func (f *Fill) open() error { |
| return fmt.Errorf("assetcache: %w", err) |
| } |
| f.token = hex.EncodeToString(b[:]) |
| - f.tmpName = f.tempName("body") |
| - tmp, err := os.OpenFile(f.tmpName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) |
| + f.bodyPath = f.tempName("body") |
| + f.gzPath = f.tempName("gz") |
| + // Read and write: Commit reads the body back to compress it. |
| + tmp, err := os.OpenFile(f.bodyPath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600) |
| if err != nil { |
| return fmt.Errorf("assetcache: %w", err) |
| } |
| @@ -168,7 +180,8 @@ func (f *Fill) open() error { |
| return nil |
| } |
| -// tempName is the path of this fill's temporary for part ("body" or "gz"). |
| +// tempName is the path of this fill's temporary for part ("body", "gz" or |
| +// "meta"). |
| func (f *Fill) tempName(part string) string { |
| return filepath.Join(f.s.cfg.Dir, f.id+".tmp-"+f.token+"."+part) |
| } |
| @@ -217,14 +230,12 @@ func (f *Fill) Abort() { |
| func (f *Fill) finish() { |
| if !f.done { |
| f.done = true |
| - if f.tmp != nil { |
| - f.tmp.Close() |
| - f.tmp = nil |
| - } |
| + f.closeFiles() |
| if f.token != "" { |
| f.left = []leftover{ |
| - {path: f.tmpName, size: f.res.identity}, |
| - {path: f.tempName("gz"), size: f.res.gzip}, |
| + {path: f.bodyPath, size: f.res.identity}, |
| + {path: f.gzPath, size: f.res.gzip}, |
| + {path: f.tempName("meta"), size: f.res.meta}, |
| } |
| } |
| f.s.releaseSlot(f.scope) |
| @@ -250,10 +261,27 @@ func (f *Fill) finish() { |
| f.held = remaining |
| } |
| +// closeFiles closes the fill's open temporaries. The caller holds f.mu. |
| +func (f *Fill) closeFiles() { |
| + if f.tmp != nil { |
| + f.tmp.Close() |
| + f.tmp = nil |
| + } |
| + if f.gz != nil { |
| + f.gz.Close() |
| + f.gz = nil |
| + } |
| +} |
| + |
| // releaseSlot returns a fill slot. |
| func (s *Store) releaseSlot(scope string) { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| + s.releaseSlotLocked(scope) |
| +} |
| + |
| +// releaseSlotLocked returns a fill slot. The caller holds s.mu. |
| +func (s *Store) releaseSlotLocked(scope string) { |
| s.fills-- |
| if s.fillsByApp[scope]--; s.fillsByApp[scope] <= 0 { |
| delete(s.fillsByApp, scope) |
| @@ -269,3 +297,258 @@ func (s *Store) releaseReserved(n int64) { |
| defer s.mu.Unlock() |
| s.reserved -= n |
| } |
| + |
| +// crashBeforeMetaRename is the Commit stage, for tests, after the meta |
| +// temporary is written and before it is renamed over <id>.meta. |
| +const crashBeforeMetaRename = "before meta rename" |
| + |
| +// errSimulatedCrash is what Commit returns when it stops at f.crashAt. It |
| +// leaves the files as a crash would and cleans up nothing. |
| +var errSimulatedCrash = errors.New("assetcache: simulated crash") |
| + |
| +// errGzipTooLarge stops the gzip copy once it would pass its limit. |
| +var errGzipTooLarge = errors.New("assetcache: gzip copy larger than its limit") |
| + |
| +// Commit stores what was written as the entry for the fill's key, replacing |
| +// any entry it already has. It sets m's Key, Version, Size, GzipSize and |
| +// StoredAt itself; the caller supplies Header, Lifetime and Expires. With |
| +// gzipCopy it also keeps a gzip copy of the body, unless that would be larger |
| +// than the body or the reservation's gzip half. |
| +// |
| +// The order makes a crash leave either the old entry or the new one, never |
| +// new bytes under old metadata: (1) gzip the body into a temporary; |
| +// (2) draw a fresh version; (3) fill in the meta; (4) encode it, refusing with |
| +// ErrTooLarge when it passes MaxMeta, before anything is renamed; (5) fsync |
| +// the bodies and rename them to their versioned names; (6) write, fsync and |
| +// rename the meta over <id>.meta; (7) retire the previous version, whose |
| +// files are unlinked at once but stay counted while a Reader holds them. The |
| +// meta's bytes are then counted with the entry and the reservation released. |
| +// |
| +// Any error before the meta rename behaves as Abort. Commit after Commit or |
| +// Abort returns os.ErrClosed and changes nothing. |
| +func (f *Fill) Commit(m Meta, gzipCopy bool) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if f.done { |
| + return os.ErrClosed |
| + } |
| + if f.failed != nil { |
| + f.finish() |
| + return f.failed |
| + } |
| + err := f.commit(m, gzipCopy) |
| + if errors.Is(err, errSimulatedCrash) { |
| + return err |
| + } |
| + if err != nil { |
| + f.finish() |
| + } |
| + return err |
| +} |
| + |
| +// commit does Commit's work. Until the meta rename every error returns with |
| +// the fill's files where finish can find and remove them; after it, commit |
| +// cannot fail. The caller holds f.mu. |
| +func (f *Fill) commit(m Meta, gzipCopy bool) error { |
| + s := f.s |
| + |
| + // (1) The gzip copy, held to the identity size and the gzip half. |
| + var gzSize int64 |
| + if gzipCopy { |
| + n, kept, err := f.writeGzip() |
| + if err != nil { |
| + return err |
| + } |
| + if kept { |
| + gzSize = n |
| + } |
| + } |
| + |
| + // (2) A fresh version, so no file an older meta names is overwritten. |
| + var b [8]byte |
| + if _, err := rand.Read(b[:]); err != nil { |
| + return fmt.Errorf("assetcache: %w", err) |
| + } |
| + version := hex.EncodeToString(b[:]) |
| + |
| + // (3) The fields the store owns. |
| + m.Key = f.key |
| + m.Version = version |
| + m.Size = f.written |
| + m.GzipSize = gzSize |
| + m.StoredAt = s.cfg.Now() |
| + |
| + // (4) The final meta must fit its reservation before anything is renamed. |
| + raw, err := encodeMeta(m) |
| + if err != nil { |
| + return fmt.Errorf("assetcache: %w", err) |
| + } |
| + if int64(len(raw)) > MaxMeta || int64(len(raw)) > f.res.meta { |
| + return ErrTooLarge |
| + } |
| + |
| + // (5) The bodies, durable under their versioned names. Nothing names |
| + // them until the meta rename, so a crash here leaves orphans Open removes. |
| + if err := f.tmp.Sync(); err != nil { |
| + return fmt.Errorf("assetcache: %w", err) |
| + } |
| + if f.gz != nil { |
| + if err := f.gz.Sync(); err != nil { |
| + return fmt.Errorf("assetcache: %w", err) |
| + } |
| + } |
| + f.closeFiles() |
| + dir := s.cfg.Dir |
| + if err := renameTo(&f.bodyPath, filepath.Join(dir, bodyName(f.id, version))); err != nil { |
| + return err |
| + } |
| + if gzSize > 0 { |
| + if err := renameTo(&f.gzPath, filepath.Join(dir, gzipName(f.id, version))); err != nil { |
| + return err |
| + } |
| + } |
| + if err := syncDir(dir); err != nil { |
| + return err |
| + } |
| + |
| + // (6) The meta, under the id lock so that the order of meta renames for |
| + // one id is the order its index slot changes in. |
| + unlock := s.lockID(f.id) |
| + metaTmp := f.tempName("meta") |
| + if err := writeSynced(metaTmp, raw); err != nil { |
| + unlock() |
| + return err |
| + } |
| + if f.crashAt == crashBeforeMetaRename { |
| + unlock() |
| + return errSimulatedCrash |
| + } |
| + if err := os.Rename(metaTmp, filepath.Join(dir, metaName(f.id))); err != nil { |
| + unlock() |
| + return fmt.Errorf("assetcache: %w", err) |
| + } |
| + // The entry is committed. A failed directory sync only means a crash |
| + // could still bring back the old entry, which the design allows. |
| + _ = syncDir(dir) |
| + |
| + // (7) Swap the index slot, count the new entry and release the |
| + // reservation and the fill slot in one step, then retire the old |
| + // version. Its bytes stay counted until its files are gone. |
| + ne := newEntry(f.id, m, int64(len(raw))) |
| + s.mu.Lock() |
| + old := s.entries[f.id] |
| + if old != nil { |
| + s.unindexLocked(old) |
| + } |
| + s.index(ne) |
| + s.reserved -= f.held |
| + s.releaseSlotLocked(f.scope) |
| + s.mu.Unlock() |
| + unlock() |
| + f.held = 0 |
| + f.left = nil |
| + f.done = true |
| + |
| + if old != nil { |
| + s.unlink(old.ver) |
| + } |
| + s.retryStuck() |
| + return nil |
| +} |
| + |
| +// writeGzip compresses the identity body into the gzip temporary, which it |
| +// leaves open in f.gz. It reports kept=false, with the temporary removed, |
| +// when the copy would be larger than the identity body or the reservation's |
| +// gzip half; no write ever passes that limit. The caller holds f.mu. |
| +func (f *Fill) writeGzip() (n int64, kept bool, err error) { |
| + out, err := os.OpenFile(f.gzPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) |
| + if err != nil { |
| + return 0, false, fmt.Errorf("assetcache: %w", err) |
| + } |
| + f.gz = out |
| + lw := &limitWriter{w: out, left: min(f.written, f.res.gzip)} |
| + zw := gzip.NewWriter(lw) |
| + _, err = io.Copy(zw, io.NewSectionReader(f.tmp, 0, f.written)) |
| + if err == nil { |
| + err = zw.Close() |
| + } |
| + if errors.Is(err, errGzipTooLarge) { |
| + f.gz.Close() |
| + f.gz = nil |
| + if err := os.Remove(f.gzPath); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return 0, false, fmt.Errorf("assetcache: %w", err) |
| + } |
| + return 0, false, nil |
| + } |
| + if err != nil { |
| + return 0, false, fmt.Errorf("assetcache: gzip copy: %w", err) |
| + } |
| + return lw.n, true, nil |
| +} |
| + |
| +// limitWriter passes writes through until one would take the total past |
| +// left; that write writes nothing and returns errGzipTooLarge. |
| +type limitWriter struct { |
| + w io.Writer |
| + left int64 |
| + n int64 |
| +} |
| + |
| +func (l *limitWriter) Write(p []byte) (int, error) { |
| + if int64(len(p)) > l.left { |
| + return 0, errGzipTooLarge |
| + } |
| + n, err := l.w.Write(p) |
| + l.left -= int64(n) |
| + l.n += int64(n) |
| + return n, err |
| +} |
| + |
| +// renameTo renames *from to to and, once it has, records the new name in |
| +// *from, so an abort removes the file wherever it is. |
| +func renameTo(from *string, to string) error { |
| + if err := os.Rename(*from, to); err != nil { |
| + return fmt.Errorf("assetcache: %w", err) |
| + } |
| + *from = to |
| + return nil |
| +} |
| + |
| +// writeSynced writes data to a new file at path and fsyncs it. |
| +func writeSynced(path string, data []byte) error { |
| + out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) |
| + if err != nil { |
| + return fmt.Errorf("assetcache: %w", err) |
| + } |
| + _, err = out.Write(data) |
| + if err == nil { |
| + err = out.Sync() |
| + } |
| + if cerr := out.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err != nil { |
| + return fmt.Errorf("assetcache: %w", err) |
| + } |
| + return nil |
| +} |
| + |
| +// syncDir fsyncs the directory, so the renames in it are durable. Windows |
| +// cannot sync a directory handle; the store does not run there. |
| +func syncDir(dir string) error { |
| + if runtime.GOOS == "windows" { |
| + return nil |
| + } |
| + d, err := os.Open(dir) |
| + if err != nil { |
| + return fmt.Errorf("assetcache: %w", err) |
| + } |
| + err = d.Sync() |
| + if cerr := d.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err != nil { |
| + return fmt.Errorf("assetcache: %w", err) |
| + } |
| + return nil |
| +} |
diff --git a/internal/assetcache/meta.go b/internal/assetcache/meta.go| index b7eedd6f8..61a4c3703 100644 |
| --- a/internal/assetcache/meta.go |
| +++ b/internal/assetcache/meta.go |
| @@ -22,6 +22,16 @@ type Meta struct { |
| GzipSize int64 |
| } |
| +// Age is how long ago, by its lifetime, the entry was fresh from the origin: |
| +// Lifetime minus the time left until Expires. It is never below zero, so an |
| +// entry stored "in the future" before a clock step reports age zero. |
| +func (m Meta) Age(now time.Time) time.Duration { |
| + if a := m.Lifetime - m.Expires.Sub(now); a > 0 { |
| + return a |
| + } |
| + return 0 |
| +} |
| + |
| func encodeMeta(m Meta) ([]byte, error) { |
| return json.Marshal(m) |
| } |
diff --git a/internal/assetcache/store.go b/internal/assetcache/store.go| index 8fa99c913..4ea3d6e39 100644 |
| --- a/internal/assetcache/store.go |
| +++ b/internal/assetcache/store.go |
| @@ -19,27 +19,60 @@ import ( |
| // Config configures a Store. |
| type Config struct { |
| Dir string // the cache directory; created 0700 |
| - Budget int64 // bytes of bodies the store may hold |
| + Budget int64 // bytes of entries (bodies and .meta files) the store may hold |
| FS FS // free-space source |
| Now func() time.Time // defaults to time.Now |
| } |
| // Stats is a snapshot of the store's accounting. |
| type Stats struct { |
| - Entries int |
| + Entries int |
| + // Bytes is the disk the store holds: every indexed entry's bodies and |
| + // .meta file, and the retired bodies counted in Retired. |
| Bytes int64 |
| Reserved int64 |
| - Apps int |
| + // Retired is the bytes of replaced, expired, evicted or swept bodies |
| + // that are unlinked but still hold disk: open Readers keep them, or an |
| + // unlink failed and will be retried. |
| + Retired int64 |
| + Apps int |
| } |
| // entry is one indexed cache entry. |
| type entry struct { |
| - id string |
| - meta Meta |
| + id string |
| + meta Meta |
| + metaSize int64 // bytes of the .meta file |
| + ver *version // the body files meta names |
| + used uint64 // the store's use counter when last returned by Get |
| } |
| -// bytes is the disk the entry's body files hold. |
| -func (e *entry) bytes() int64 { return e.meta.Size + e.meta.GzipSize } |
| +func newEntry(id string, m Meta, metaSize int64) *entry { |
| + return &entry{id: id, meta: m, metaSize: metaSize, ver: &version{id: id, v: m.Version, bytes: m.Size + m.GzipSize}} |
| +} |
| + |
| +// bytes is the disk the entry's files hold. |
| +func (e *entry) bytes() int64 { return e.metaSize + e.ver.bytes } |
| + |
| +// version is one committed version's body files, <id>.<v>.body and |
| +// <id>.<v>.gz. Its bytes stay counted in Store.used while any of indexed, |
| +// leases, unlinking or stuck holds: the disk is not free until the files are |
| +// unlinked and the last Reader has closed them. Fields are guarded by s.mu. |
| +type version struct { |
| + id, v string |
| + bytes int64 |
| + indexed bool // an indexed entry names this version |
| + leases int // open Readers |
| + unlinking bool // an unlink is in progress |
| + stuck bool // an unlink failed; retryStuck tries again |
| + counted bool // bytes are in s.used |
| +} |
| + |
| +// idLock serializes the changes to one id's .meta file and its index slot. |
| +type idLock struct { |
| + mu sync.Mutex |
| + refs int // guarded by Store.mu |
| +} |
| // Store is a bounded disk cache over one directory. |
| type Store struct { |
| @@ -48,10 +81,14 @@ type Store struct { |
| mu sync.Mutex |
| entries map[string]*entry // by id |
| apps map[string]map[string]*entry // AppScope -> id -> entry |
| - used int64 // bytes held by indexed entries |
| + used int64 // bytes held by entries and retired versions |
| + retired int64 // the part of used no indexed entry names |
| reserved int64 // bytes promised to fills in flight |
| fills int // fills in flight on this box |
| fillsByApp map[string]int // fills in flight by AppScope |
| + useCount uint64 // ticks once per Get hit |
| + idLocks map[string]*idLock // by id, while held or awaited |
| + stuck map[*version]struct{} // retired versions whose unlink failed |
| } |
| // Open creates the directory if needed and rebuilds the index from it. |
| @@ -80,6 +117,8 @@ func Open(cfg Config) (*Store, error) { |
| apps: make(map[string]map[string]*entry), |
| fillsByApp: make(map[string]int), |
| + idLocks: make(map[string]*idLock), |
| + stuck: make(map[*version]struct{}), |
| } |
| if err := s.scan(); err != nil { |
| return nil, err |
| @@ -113,7 +152,7 @@ func (s *Store) scan() error { |
| keep := make(map[string]bool) // body file names a parsed meta names |
| for _, name := range metas { |
| id := strings.TrimSuffix(name, ".meta") |
| - m, valid, err := s.loadMeta(id) |
| + m, metaSize, valid, err := s.loadMeta(id) |
| if err != nil { |
| return err |
| } |
| @@ -127,10 +166,11 @@ func (s *Store) scan() error { |
| if m.GzipSize > 0 { |
| keep[gzipName(id, m.Version)] = true |
| } |
| - if s.used > math.MaxInt64-(m.Size+m.GzipSize) { |
| + e := newEntry(id, m, metaSize) |
| + if e.ver.bytes > math.MaxInt64-metaSize || s.used > math.MaxInt64-e.bytes() { |
| return errors.New("assetcache: indexed bytes overflow") |
| } |
| - s.index(&entry{id: id, meta: m}) |
| + s.index(e) |
| } |
| for _, name := range files { |
| if !keep[name] { |
| @@ -146,30 +186,31 @@ func (s *Store) scan() error { |
| // that is certainly broken: a missing or malformed meta, one that belongs to |
| // another key, or one whose body files are missing or not the size it |
| // records. Any other failure to read the disk is returned as an error, so a |
| -// permission or I/O fault never leads to deleting a good entry. |
| -func (s *Store) loadMeta(id string) (m Meta, valid bool, err error) { |
| +// permission or I/O fault never leads to deleting a good entry. metaSize is |
| +// the .meta file's length. |
| +func (s *Store) loadMeta(id string) (m Meta, metaSize int64, valid bool, err error) { |
| raw, err := os.ReadFile(filepath.Join(s.cfg.Dir, metaName(id))) |
| if errors.Is(err, os.ErrNotExist) { |
| - return Meta{}, false, nil |
| + return Meta{}, 0, false, nil |
| } |
| if err != nil { |
| - return Meta{}, false, fmt.Errorf("assetcache: %w", err) |
| + return Meta{}, 0, false, fmt.Errorf("assetcache: %w", err) |
| } |
| m, err = decodeMeta(raw) |
| if err != nil || m.Key.ID() != id { |
| - return Meta{}, false, nil |
| + return Meta{}, 0, false, nil |
| } |
| ok, err := s.bodyMatches(bodyName(id, m.Version), m.Size) |
| if err != nil || !ok { |
| - return Meta{}, false, err |
| + return Meta{}, 0, false, err |
| } |
| if m.GzipSize > 0 { |
| ok, err = s.bodyMatches(gzipName(id, m.Version), m.GzipSize) |
| if err != nil || !ok { |
| - return Meta{}, false, err |
| + return Meta{}, 0, false, err |
| } |
| } |
| - return m, true, nil |
| + return m, int64(len(raw)), true, nil |
| } |
| // bodyMatches reports whether the named file is a regular file of exactly |
| @@ -193,8 +234,8 @@ func (s *Store) remove(name string) error { |
| return nil |
| } |
| -// index adds e to the in-memory index. The caller holds s.mu or has not yet |
| -// shared s. |
| +// index adds e, whose id has no indexed entry, to the in-memory index and |
| +// counts its files. The caller holds s.mu or has not yet shared s. |
| func (s *Store) index(e *entry) { |
| s.entries[e.id] = e |
| scope := e.meta.Key.AppScope() |
| @@ -204,9 +245,225 @@ func (s *Store) index(e *entry) { |
| s.apps[scope] = app |
| } |
| app[e.id] = e |
| + e.ver.indexed = true |
| + e.ver.counted = true |
| s.used += e.bytes() |
| } |
| +// unindexLocked takes e out of the index and retires its version: the .meta |
| +// bytes stop counting (the caller has removed or replaced the file), the body |
| +// bytes stay counted until unlink has removed them and the last lease has |
| +// closed. The caller holds s.mu and, once it has released s.mu, must call |
| +// s.unlink(e.ver). |
| +func (s *Store) unindexLocked(e *entry) { |
| + delete(s.entries, e.id) |
| + scope := e.meta.Key.AppScope() |
| + if app := s.apps[scope]; app != nil { |
| + delete(app, e.id) |
| + if len(app) == 0 { |
| + delete(s.apps, scope) |
| + } |
| + } |
| + s.used -= e.metaSize |
| + v := e.ver |
| + v.indexed = false |
| + v.unlinking = true |
| + s.retired += v.bytes |
| +} |
| + |
| +// unlink removes a retired version's body files at once, whether or not a |
| +// Reader still holds them (an unlinked open file stays readable), then |
| +// settles its accounting. A failed removal leaves the version stuck: its bytes |
| +// stay counted and retryStuck tries again. It is called without s.mu held. |
| +func (s *Store) unlink(v *version) { |
| + err := errors.Join(s.remove(bodyName(v.id, v.v)), s.remove(gzipName(v.id, v.v))) |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + v.unlinking = false |
| + if err != nil { |
| + v.stuck = true |
| + s.stuck[v] = struct{}{} |
| + } else if v.stuck { |
| + v.stuck = false |
| + delete(s.stuck, v) |
| + } |
| + s.settleLocked(v) |
| +} |
| + |
| +// retryStuck retries the removal of versions whose unlink failed. It is |
| +// called without s.mu held. |
| +func (s *Store) retryStuck() { |
| + s.mu.Lock() |
| + var vs []*version |
| + for v := range s.stuck { |
| + if !v.unlinking { |
| + v.unlinking = true |
| + vs = append(vs, v) |
| + } |
| + } |
| + s.mu.Unlock() |
| + for _, v := range vs { |
| + s.unlink(v) |
| + } |
| +} |
| + |
| +// settleLocked stops counting v's bytes once nothing holds them. The caller |
| +// holds s.mu. |
| +func (s *Store) settleLocked(v *version) { |
| + if v.counted && !v.indexed && v.leases == 0 && !v.unlinking && !v.stuck { |
| + v.counted = false |
| + s.used -= v.bytes |
| + s.retired -= v.bytes |
| + } |
| +} |
| + |
| +// lockID takes the lock for one id's .meta file and index slot, and returns |
| +// the function that releases it. Lock order: a Fill's mu, then an id lock, |
| +// then s.mu. It is called without s.mu held. |
| +func (s *Store) lockID(id string) (unlock func()) { |
| + s.mu.Lock() |
| + l := s.idLocks[id] |
| + if l == nil { |
| + l = &idLock{} |
| + s.idLocks[id] = l |
| + } |
| + l.refs++ |
| + s.mu.Unlock() |
| + l.mu.Lock() |
| + return func() { |
| + l.mu.Unlock() |
| + s.mu.Lock() |
| + if l.refs--; l.refs == 0 { |
| + delete(s.idLocks, id) |
| + } |
| + s.mu.Unlock() |
| + } |
| +} |
| + |
| +// drop deletes the indexed entry e: its .meta first, so a crash part way |
| +// leaves only orphan bodies that Open removes, then its bodies, subject to |
| +// leases. It deletes nothing and reports false when e is no longer the |
| +// indexed entry for its id, or when its .meta cannot be removed (the entry |
| +// then stays indexed and counted). Get's expiry uses it; eviction, Retain and |
| +// the sweep are to use it too. It is called without s.mu held. |
| +func (s *Store) drop(e *entry) bool { |
| + unlock := s.lockID(e.id) |
| + s.mu.Lock() |
| + current := s.entries[e.id] == e |
| + s.mu.Unlock() |
| + if !current { |
| + unlock() |
| + return false |
| + } |
| + if err := s.remove(metaName(e.id)); err != nil { |
| + unlock() |
| + return false |
| + } |
| + s.mu.Lock() |
| + s.unindexLocked(e) |
| + s.mu.Unlock() |
| + unlock() |
| + s.unlink(e.ver) |
| + s.retryStuck() |
| + return true |
| +} |
| + |
| +// Entry is a cache hit: the metadata as stored, and the means to open its |
| +// bodies. Its Header is the caller's own copy. |
| +type Entry struct { |
| + Meta Meta |
| + |
| + s *Store |
| + ver *version |
| +} |
| + |
| +// Get returns the entry for k and marks it recently used. An entry whose |
| +// expiry has come (Now at or past Meta.Expires) is not returned: it is |
| +// deleted. |
| +func (s *Store) Get(k Key) (*Entry, bool) { |
| + id := k.ID() |
| + now := s.cfg.Now() |
| + s.mu.Lock() |
| + e := s.entries[id] |
| + if e == nil || e.meta.Key != k { |
| + s.mu.Unlock() |
| + return nil, false |
| + } |
| + if !now.Before(e.meta.Expires) { |
| + s.mu.Unlock() |
| + s.drop(e) |
| + return nil, false |
| + } |
| + s.useCount++ |
| + e.used = s.useCount |
| + out := &Entry{Meta: e.meta, s: s, ver: e.ver} |
| + out.Meta.Header = e.meta.Header.Clone() |
| + s.mu.Unlock() |
| + return out, true |
| +} |
| + |
| +// Open opens the identity body, or the gzip copy when gzip is true. The |
| +// Reader holds a lease on the entry's version: if the entry is replaced, |
| +// evicted or expired while it is open, its files are unlinked at once but |
| +// their bytes stay counted until the Reader closes. Open fails once the |
| +// version has been retired, and for gzip when the entry has no gzip copy. |
| +func (e *Entry) Open(gzip bool) (*Reader, error) { |
| + if e.s == nil { |
| + return nil, errors.New("assetcache: entry not from a store") |
| + } |
| + name := bodyName(e.ver.id, e.ver.v) |
| + if gzip { |
| + if e.Meta.GzipSize == 0 { |
| + return nil, fmt.Errorf("assetcache: no gzip copy: %w", os.ErrNotExist) |
| + } |
| + name = gzipName(e.ver.id, e.ver.v) |
| + } |
| + s := e.s |
| + s.mu.Lock() |
| + if !e.ver.indexed { |
| + s.mu.Unlock() |
| + return nil, fmt.Errorf("assetcache: entry replaced or deleted: %w", os.ErrNotExist) |
| + } |
| + e.ver.leases++ // before the open, so a retirement from here on keeps the bytes counted |
| + s.mu.Unlock() |
| + f, err := os.Open(filepath.Join(s.cfg.Dir, name)) |
| + if err != nil { |
| + s.release(e.ver) |
| + return nil, fmt.Errorf("assetcache: %w", err) |
| + } |
| + return &Reader{f: f, s: s, ver: e.ver}, nil |
| +} |
| + |
| +// release returns one lease on v. |
| +func (s *Store) release(v *version) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + v.leases-- |
| + s.settleLocked(v) |
| +} |
| + |
| +// Reader reads one body file of an entry. It is an io.ReadSeeker, as |
| +// http.ServeContent needs, and an io.ReaderAt. Close releases its lease. |
| +type Reader struct { |
| + f *os.File |
| + s *Store |
| + ver *version |
| + once sync.Once |
| +} |
| + |
| +func (r *Reader) Read(p []byte) (int, error) { return r.f.Read(p) } |
| +func (r *Reader) ReadAt(p []byte, off int64) (int, error) { return r.f.ReadAt(p, off) } |
| +func (r *Reader) Seek(offset int64, whence int) (int64, error) { return r.f.Seek(offset, whence) } |
| +func (r *Reader) Stat() (os.FileInfo, error) { return r.f.Stat() } |
| + |
| +// Close closes the file and then releases the lease, exactly once however |
| +// often it is called. |
| +func (r *Reader) Close() error { |
| + err := r.f.Close() |
| + r.once.Do(func() { r.s.release(r.ver) }) |
| + return err |
| +} |
| + |
| // Stats reports the store's current accounting. |
| func (s *Store) Stats() Stats { |
| s.mu.Lock() |
| @@ -215,6 +472,7 @@ func (s *Store) Stats() Stats { |
| Entries: len(s.entries), |
| Bytes: s.used, |
| Reserved: s.reserved, |
| + Retired: s.retired, |
| Apps: len(s.apps), |
| } |
| } |
diff --git a/internal/assetcache/store_test.go b/internal/assetcache/store_test.go| index bd16ae149..a34415734 100644 |
| --- a/internal/assetcache/store_test.go |
| +++ b/internal/assetcache/store_test.go |
| @@ -81,6 +81,17 @@ func sameNames(t *testing.T, got, want []string) { |
| } |
| } |
| +// metaFile is the size of k's .meta file, which the store counts with the |
| +// entry's bodies. |
| +func metaFile(t *testing.T, dir string, k Key) int64 { |
| + t.Helper() |
| + fi, err := os.Stat(filepath.Join(dir, k.ID()+".meta")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return fi.Size() |
| +} |
| + |
| func openStore(t *testing.T, dir string) *Store { |
| t.Helper() |
| s, err := Open(testConfig(dir)) |
| @@ -157,7 +168,7 @@ func TestOpenRemovesOrphanBodiesAndTemporaries(t *testing.T) { |
| s := openStore(t, dir) |
| sameNames(t, listDir(t, dir), []string{"README", kept.ID() + ".a.body", kept.ID() + ".a.gz", kept.ID() + ".meta"}) |
| - if st := s.Stats(); st.Entries != 1 || st.Bytes != int64(len("body")+len("gz")) { |
| + if st := s.Stats(); st.Entries != 1 || st.Bytes != int64(len("body")+len("gz"))+metaFile(t, dir, kept) { |
| t.Fatalf("Stats = %+v, want 1 entry of 6 bytes", st) |
| } |
| } |
| @@ -182,7 +193,7 @@ func TestOpenKeepsMetaWithUnknownFields(t *testing.T) { |
| writeVersionFiles(t, dir, k.ID(), "a", []byte("body"), nil) |
| st := openStore(t, dir).Stats() |
| - if st.Entries != 1 || st.Bytes != 4 { |
| + if st.Entries != 1 || st.Bytes != 4+metaFile(t, dir, k) { |
| t.Fatalf("Stats = %+v, want the entry kept", st) |
| } |
| sameNames(t, listDir(t, dir), []string{k.ID() + ".meta", k.ID() + ".a.body"}) |
| @@ -218,7 +229,7 @@ func TestOpenDropsUnparseableMeta(t *testing.T) { |
| writeFile(t, filepath.Join(dir, evil.ID()+".meta"), raw) |
| st := openStore(t, dir).Stats() |
| - if st.Entries != 2 || st.Bytes != int64(len("good")+len("other")) { |
| + if st.Entries != 2 || st.Bytes != int64(len("good")+len("other"))+metaFile(t, dir, good)+metaFile(t, dir, other) { |
| t.Fatalf("Stats = %+v, want only the good and other entries", st) |
| } |
| sameNames(t, listDir(t, dir), []string{ |
| @@ -249,7 +260,8 @@ func TestOpenIndexesExistingEntries(t *testing.T) { |
| s := openStore(t, dir) |
| st := s.Stats() |
| - want := Stats{Entries: 3, Bytes: 4 + 2 + 6 + 2, Reserved: 0, Apps: 2} |
| + metas := metaFile(t, dir, testKey("shop", "/a.css")) + metaFile(t, dir, testKey("shop", "/b.js")) + metaFile(t, dir, testKey("blog", "/c.png")) |
| + want := Stats{Entries: 3, Bytes: 4 + 2 + 6 + 2 + metas, Reserved: 0, Apps: 2} |
| if st != want { |
| t.Fatalf("Stats = %+v, want %+v", st, want) |
| } |
| @@ -267,8 +279,8 @@ func TestOpenDeletesSupersededVersions(t *testing.T) { |
| s := openStore(t, dir) |
| sameNames(t, listDir(t, dir), []string{k.ID() + ".b.body", k.ID() + ".b.gz", k.ID() + ".meta"}) |
| - if st := s.Stats(); st.Entries != 1 || st.Bytes != 4 { |
| - t.Fatalf("Stats = %+v, want 1 entry of 4 bytes", st) |
| + if st := s.Stats(); st.Entries != 1 || st.Bytes != 4+metaFile(t, dir, k) { |
| + t.Fatalf("Stats = %+v, want 1 entry of 4 bytes and its meta", st) |
| } |
| } |
| @@ -294,7 +306,7 @@ func TestOpenFailsOnUnreadableMetaAndKeepsEntry(t *testing.T) { |
| if err := os.Chmod(metaPath, 0o600); err != nil { |
| t.Fatal(err) |
| } |
| - if st := openStore(t, dir).Stats(); st.Entries != 1 || st.Bytes != 6 { |
| + if st := openStore(t, dir).Stats(); st.Entries != 1 || st.Bytes != 6+metaFile(t, dir, k) { |
| t.Fatalf("Stats = %+v, want the entry intact", st) |
| } |
| } |