carlos / platform Public

assetcache: reservations, the free-space floor and fill bounds

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev f57c9a00aa6ad99adcbde784b3ba94e57bbfc037 parent 71fee2f
3 files changed, +593 −5
  • internal/assetcache/fill.go +231 −0
  • internal/assetcache/fill_test.go +350 −0
  • internal/assetcache/store.go +12 −5
diff --git a/internal/assetcache/fill.go b/internal/assetcache/fill.go
new file mode 100644
index 000000000..b321a25a2
--- /dev/null
+++ b/internal/assetcache/fill.go
@@ -0,0 +1,231 @@
+package assetcache
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sync"
+)
+
+const (
+ // MaxBody is the largest identity body the store will hold.
+ MaxBody = 32 << 20
+
+ // metaReserve is the disk a reservation sets aside for the .meta file.
+ metaReserve = 64 << 10
+
+ // maxFillsPerBox and maxFillsPerApp bound the fills in flight.
+ maxFillsPerBox = 16
+ maxFillsPerApp = 4
+
+ // floorPercent is the share of the filesystem that must stay free.
+ floorPercent = 15
+)
+
+var (
+ // ErrNoRoom means the budget has no room for the fill, even after eviction.
+ ErrNoRoom = errors.New("assetcache: no room in the budget")
+ // ErrBelowFloor means admitting the fill could take the disk below its
+ // free-space floor.
+ ErrBelowFloor = errors.New("assetcache: free space would fall below the floor")
+ // ErrBusy means the box or the app already has as many fills in flight
+ // as it may.
+ ErrBusy = errors.New("assetcache: too many fills in flight")
+ // ErrTooLarge means the body is, or has grown, past what the fill reserved.
+ ErrTooLarge = errors.New("assetcache: body too large")
+)
+
+// reservation is the disk a fill has set aside: room for the identity body,
+// for its gzip copy, and for the metadata file. Commit holds each to its own
+// half.
+type reservation struct {
+ identity int64
+ gzip int64
+ meta int64
+}
+
+func (r reservation) total() int64 { return r.identity + r.gzip + r.meta }
+
+// Fill is one fill in flight. Write the identity body into it. It holds a
+// reservation and one fill slot until it is committed or aborted.
+type Fill struct {
+ s *Store
+ key Key
+ scope string
+ 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 reservation is released
+}
+
+// Reserve admits a fill for k, or says why not. contentLength is the length
+// the origin announced; negative means unknown. It sets aside twice the body
+// (identity plus gzip copy) and metaReserve, taking the body as MaxBody when
+// the length is unknown.
+func (s *Store) Reserve(k Key, contentLength int64) (*Fill, error) {
+ if contentLength > MaxBody {
+ return nil, ErrTooLarge
+ }
+ n := contentLength
+ if n < 0 {
+ n = MaxBody
+ }
+ res := reservation{identity: n, gzip: n, meta: metaReserve}
+ scope := k.AppScope()
+
+ s.mu.Lock()
+ err := s.busyLocked(scope)
+ s.mu.Unlock()
+ if err != nil {
+ return nil, err
+ }
+
+ total, free, err := s.cfg.FS.Space(s.cfg.Dir)
+ if err != nil {
+ return nil, fmt.Errorf("assetcache: free space: %w", err)
+ }
+
+ s.makeRoom(res.total())
+
+ if err := s.admit(scope, res.total(), total, free); err != nil {
+ return nil, err
+ }
+ f := &Fill{s: s, key: k, scope: scope, id: k.ID(), res: res}
+ if err := f.open(); err != nil {
+ f.finish()
+ return nil, err
+ }
+ return f, nil
+}
+
+// busyLocked reports ErrBusy when a new fill for scope would pass a bound.
+func (s *Store) busyLocked(scope string) error {
+ if s.fills >= maxFillsPerBox || s.fillsByApp[scope] >= maxFillsPerApp {
+ return ErrBusy
+ }
+ return nil
+}
+
+// admit checks the bounds, the budget and the floor together and, if all
+// hold, claims the reservation and a fill slot. total and free are the
+// filesystem's size and free bytes as just measured.
+func (s *Store) admit(scope string, r int64, total, free uint64) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if err := s.busyLocked(scope); err != nil {
+ return err
+ }
+ if s.used > s.cfg.Budget-s.reserved-r { // used + reserved + r > Budget, without overflow
+ return ErrNoRoom
+ }
+ // Free space after every outstanding reservation and this one must stay
+ // at or above the floor. Reservations may already be partly written, so
+ // this counts some bytes twice: it errs towards refusing.
+ if need := uint64(s.reserved) + uint64(r) + total*floorPercent/100; free < need {
+ return ErrBelowFloor
+ }
+ s.reserved += r
+ s.fills++
+ s.fillsByApp[scope]++
+ return nil
+}
+
+// makeRoom frees budget for a reservation of need bytes by evicting entries.
+// It is called without s.mu held.
+func (s *Store) makeRoom(need int64) {}
+
+// open creates the identity temporary. Its name carries ".tmp-", so a crash
+// leaves something Open removes.
+func (f *Fill) open() error {
+ var b [8]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ 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)
+ if err != nil {
+ return fmt.Errorf("assetcache: %w", err)
+ }
+ f.tmp = tmp
+ return nil
+}
+
+// tempName is the path of this fill's temporary for part ("body" or "gz").
+func (f *Fill) tempName(part string) string {
+ return filepath.Join(f.s.cfg.Dir, f.id+".tmp-"+f.token+"."+part)
+}
+
+// Write appends to the identity body. A write that would pass the
+// reservation's identity half, or MaxBody, writes nothing, returns
+// ErrTooLarge and fails the fill for good.
+func (f *Fill) Write(p []byte) (int, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.done {
+ return 0, os.ErrClosed
+ }
+ if f.failed != nil {
+ return 0, f.failed
+ }
+ if int64(len(p)) > f.res.identity-f.written || int64(len(p)) > MaxBody-f.written {
+ f.failed = ErrTooLarge
+ return 0, f.failed
+ }
+ n, err := f.tmp.Write(p)
+ f.written += int64(n)
+ if err != nil {
+ f.failed = fmt.Errorf("assetcache: %w", err)
+ return n, f.failed
+ }
+ return n, nil
+}
+
+// Abort deletes the fill's temporaries and releases its reservation and fill
+// slot. It is safe to call twice and after Commit.
+func (f *Fill) Abort() {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.done {
+ return
+ }
+ f.finish()
+}
+
+// finish closes and removes the temporaries, then releases the reservation
+// and the slot, once. The caller holds f.mu, or has not shared f.
+func (f *Fill) finish() {
+ if f.done {
+ return
+ }
+ f.done = true
+ if f.tmp != nil {
+ f.tmp.Close()
+ f.tmp = nil
+ }
+ if f.token != "" {
+ os.Remove(f.tmpName)
+ os.Remove(f.tempName("gz"))
+ }
+ f.s.release(f.scope, f.res.total())
+}
+
+// release returns a reservation and its fill slot.
+func (s *Store) release(scope string, r int64) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.reserved -= r
+ s.fills--
+ if s.fillsByApp[scope]--; s.fillsByApp[scope] <= 0 {
+ delete(s.fillsByApp, scope)
+ }
+}
diff --git a/internal/assetcache/fill_test.go b/internal/assetcache/fill_test.go
new file mode 100644
index 000000000..6fd331524
--- /dev/null
+++ b/internal/assetcache/fill_test.go
@@ -0,0 +1,350 @@
+package assetcache
+
+import (
+ "errors"
+ "fmt"
+ "sync"
+ "testing"
+)
+
+// fakeFS is a settable free-space source. Tests using it are not acceptance:
+// the real FS is covered by TestStatfsReportsTheTempDir.
+type fakeFS struct {
+ mu sync.Mutex
+ total, free uint64
+ err error
+}
+
+func (f *fakeFS) Space(string) (uint64, uint64, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.total, f.free, f.err
+}
+
+func (f *fakeFS) setFree(v uint64) {
+ f.mu.Lock()
+ f.free = v
+ f.mu.Unlock()
+}
+
+const worstReserve = 2*MaxBody + metaReserve
+
+// fillStore opens a Store over a real temporary directory with a fake FS that
+// has plenty of room, and a budget big enough for many worst-case fills.
+func fillStore(t *testing.T) (*Store, *fakeFS, string) {
+ t.Helper()
+ dir := t.TempDir()
+ fs := &fakeFS{total: 64 << 30, free: 64 << 30}
+ cfg := testConfig(dir)
+ cfg.Budget = 4 << 30
+ cfg.FS = fs
+ s, err := Open(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s, fs, dir
+}
+
+// TestReserveWorstCaseWithUnknownLength is not acceptance: it uses a fake FS.
+func TestReserveWorstCaseWithUnknownLength(t *testing.T) {
+ s, _, _ := fillStore(t)
+ f, err := s.Reserve(testKey("shop", "/a.css"), -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Abort()
+ if got, want := s.Stats().Reserved, int64(2*MaxBody+64<<10); got != want {
+ t.Fatalf("Reserved = %d, want %d", got, want)
+ }
+}
+
+// TestReserveUsesContentLength is not acceptance: it uses a fake FS.
+func TestReserveUsesContentLength(t *testing.T) {
+ s, _, _ := fillStore(t)
+ f, err := s.Reserve(testKey("shop", "/a.css"), 1000)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Abort()
+ if got, want := s.Stats().Reserved, int64(2*1000+metaReserve); got != want {
+ t.Fatalf("Reserved = %d, want %d", got, want)
+ }
+}
+
+// TestReserveRefusesTooLarge is not acceptance: it uses a fake FS.
+func TestReserveRefusesTooLarge(t *testing.T) {
+ s, _, dir := fillStore(t)
+ if _, err := s.Reserve(testKey("shop", "/big"), MaxBody+1); !errors.Is(err, ErrTooLarge) {
+ t.Fatalf("err = %v, want ErrTooLarge", err)
+ }
+ f, err := s.Reserve(testKey("shop", "/max"), MaxBody)
+ if err != nil {
+ t.Fatalf("a body of exactly MaxBody: %v", err)
+ }
+ f.Abort()
+ if got := s.Stats().Reserved; got != 0 {
+ t.Fatalf("Reserved = %d after refusals and abort, want 0", got)
+ }
+ if got := listDir(t, dir); len(got) != 0 {
+ t.Fatalf("files left: %v", got)
+ }
+}
+
+// TestReserveRefusesBelowTheFloor is not acceptance: it uses a fake FS. It is
+// spec section 7's sixteen-fill case reduced to its rule: free space minus
+// outstanding reservations minus this one must stay at the 15% floor.
+func TestReserveRefusesBelowTheFloor(t *testing.T) {
+ s, fs, _ := fillStore(t)
+ fs.total = 8 << 30
+ fs.free = 8<<30*15/100 + worstReserve // exactly one reservation above the floor
+ first, err := s.Reserve(testKey("shop", "/a"), -1)
+ if err != nil {
+ t.Fatalf("first reservation: %v", err)
+ }
+ defer first.Abort()
+ if _, err := s.Reserve(testKey("blog", "/b"), -1); !errors.Is(err, ErrBelowFloor) {
+ t.Fatalf("second concurrent reservation: err = %v, want ErrBelowFloor", err)
+ }
+ if got := s.Stats().Reserved; got != worstReserve {
+ t.Fatalf("Reserved = %d after a refusal, want %d", got, int64(worstReserve))
+ }
+ // Once the first is released the room is back.
+ first.Abort()
+ again, err := s.Reserve(testKey("blog", "/b"), -1)
+ if err != nil {
+ t.Fatalf("after abort: %v", err)
+ }
+ again.Abort()
+}
+
+// TestReserveRefusesWhenSomethingElseFillsTheDisk is not acceptance: it uses a
+// fake FS. Free space drops between two calls, as when logs fill the disk.
+func TestReserveRefusesWhenSomethingElseFillsTheDisk(t *testing.T) {
+ s, fs, _ := fillStore(t)
+ fs.total = 8 << 30
+ fs.setFree(4 << 30)
+ f, err := s.Reserve(testKey("shop", "/a"), -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Abort()
+ fs.setFree(8 << 30 * 15 / 100) // the floor itself, nothing to spare
+ if _, err := s.Reserve(testKey("shop", "/b"), 10); !errors.Is(err, ErrBelowFloor) {
+ t.Fatalf("err = %v, want ErrBelowFloor", err)
+ }
+ // The fill in flight is untouched and still writes up to its reservation.
+ if _, err := f.Write([]byte("still fine")); err != nil {
+ t.Fatalf("in-flight write: %v", err)
+ }
+}
+
+// TestReserveRefusesWithAnFSError is not acceptance: it uses a fake FS.
+func TestReserveRefusesWithAnFSError(t *testing.T) {
+ s, fs, _ := fillStore(t)
+ boom := errors.New("statfs failed")
+ fs.err = boom
+ if _, err := s.Reserve(testKey("shop", "/a"), 10); !errors.Is(err, boom) {
+ t.Fatalf("err = %v, want the FS error", err)
+ }
+ if got := s.Stats().Reserved; got != 0 {
+ t.Fatalf("Reserved = %d after an FS error", got)
+ }
+ s.mu.Lock()
+ boxFills := s.fills
+ s.mu.Unlock()
+ if boxFills != 0 {
+ t.Fatalf("fill slots held after an FS error: %d", boxFills)
+ }
+}
+
+// TestReserveRefusesOverBudget is not acceptance: it uses a fake FS.
+func TestReserveRefusesOverBudget(t *testing.T) {
+ dir := t.TempDir()
+ cfg := testConfig(dir)
+ cfg.Budget = 2*500 + metaReserve + 10 // room for one 500-byte fill, not two
+ cfg.FS = &fakeFS{total: 64 << 30, free: 64 << 30}
+ s, err := Open(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ a, err := s.Reserve(testKey("shop", "/a"), 500)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer a.Abort()
+ if _, err := s.Reserve(testKey("shop", "/b"), 500); !errors.Is(err, ErrNoRoom) {
+ t.Fatalf("err = %v, want ErrNoRoom", err)
+ }
+}
+
+// TestReserveBoundsFillsPerBoxAndPerApp is not acceptance: it uses a fake FS.
+func TestReserveBoundsFillsPerBoxAndPerApp(t *testing.T) {
+ s, _, _ := fillStore(t)
+ var fills []*Fill
+ defer func() {
+ for _, f := range fills {
+ f.Abort()
+ }
+ }()
+ reserve := func(app string, i int) (*Fill, error) {
+ f, err := s.Reserve(testKey(app, fmt.Sprintf("/%d", i)), 100)
+ if err == nil {
+ fills = append(fills, f)
+ }
+ return f, err
+ }
+
+ // Four fills for one app are fine, the fifth is busy.
+ for i := 0; i < maxFillsPerApp; i++ {
+ if _, err := reserve("shop", i); err != nil {
+ t.Fatalf("fill %d for shop: %v", i, err)
+ }
+ }
+ if _, err := reserve("shop", 99); !errors.Is(err, ErrBusy) {
+ t.Fatalf("5th fill for one app: err = %v, want ErrBusy", err)
+ }
+ // Another app is not held up by it.
+ for i := 0; i < maxFillsPerApp; i++ {
+ if _, err := reserve("blog", i); err != nil {
+ t.Fatalf("fill %d for blog: %v", i, err)
+ }
+ }
+ // Fill the box to 16 with further apps, then the 17th is busy.
+ for a := 0; len(fills) < maxFillsPerBox; a++ {
+ if _, err := reserve(fmt.Sprintf("app%d", a), 0); err != nil {
+ t.Fatalf("fill %d: %v", len(fills), err)
+ }
+ }
+ if _, err := reserve("other", 0); !errors.Is(err, ErrBusy) {
+ t.Fatalf("17th fill on the box: err = %v, want ErrBusy", err)
+ }
+ // Releasing one frees a slot for the box and for that app.
+ fills[0].Abort()
+ fills = fills[1:]
+ if _, err := reserve("shop", 100); err != nil {
+ t.Fatalf("after abort: %v", err)
+ }
+}
+
+// TestWritePastTheReservationFails is not acceptance: it uses a fake FS.
+func TestWritePastTheReservationFails(t *testing.T) {
+ s, _, _ := fillStore(t)
+ f, err := s.Reserve(testKey("shop", "/a"), 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Abort()
+ if n, err := f.Write([]byte("0123456789")); err != nil || n != 10 {
+ t.Fatalf("write of exactly the reservation: n=%d err=%v", n, err)
+ }
+ if n, err := f.Write([]byte("x")); !errors.Is(err, ErrTooLarge) || n != 0 {
+ t.Fatalf("write past the reservation: n=%d err=%v, want 0 and ErrTooLarge", n, err)
+ }
+ if _, err := f.Write(nil); !errors.Is(err, ErrTooLarge) {
+ t.Fatalf("a failed fill keeps failing: err = %v", err)
+ }
+}
+
+// TestWritePastMaxBodyFails is not acceptance: it uses a fake FS. With an
+// unknown length the identity half is MaxBody, and the fill stops there.
+func TestWritePastMaxBodyFails(t *testing.T) {
+ s, _, _ := fillStore(t)
+ f, err := s.Reserve(testKey("shop", "/a"), -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Abort()
+ chunk := make([]byte, 1<<20)
+ for i := 0; i < MaxBody>>20; i++ {
+ if _, err := f.Write(chunk); err != nil {
+ t.Fatalf("chunk %d: %v", i, err)
+ }
+ }
+ if _, err := f.Write([]byte("x")); !errors.Is(err, ErrTooLarge) {
+ t.Fatalf("byte past MaxBody: err = %v, want ErrTooLarge", err)
+ }
+}
+
+// TestAbortReleasesEverything is not acceptance: it uses a fake FS.
+func TestAbortReleasesEverything(t *testing.T) {
+ s, _, dir := fillStore(t)
+ f, err := s.Reserve(testKey("shop", "/a"), 100)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.Write([]byte("some bytes")); err != nil {
+ t.Fatal(err)
+ }
+ if len(listDir(t, dir)) == 0 {
+ t.Fatal("expected a temporary while the fill is open")
+ }
+ f.Abort()
+ if got := s.Stats().Reserved; got != 0 {
+ t.Fatalf("Reserved = %d after Abort", got)
+ }
+ if got := listDir(t, dir); len(got) != 0 {
+ t.Fatalf("files left after Abort: %v", got)
+ }
+ s.mu.Lock()
+ boxFills, appFills := s.fills, len(s.fillsByApp)
+ s.mu.Unlock()
+ if boxFills != 0 || appFills != 0 {
+ t.Fatalf("slots after Abort: box %d, apps %d, want 0 and 0", boxFills, appFills)
+ }
+ if _, err := f.Write([]byte("x")); err == nil {
+ t.Fatal("write after Abort succeeded")
+ }
+}
+
+// TestAbortTwiceIsSafe is not acceptance: it uses a fake FS. A second Abort
+// must not release another fill's reservation.
+func TestAbortTwiceIsSafe(t *testing.T) {
+ s, _, _ := fillStore(t)
+ a, err := s.Reserve(testKey("shop", "/a"), 100)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := s.Reserve(testKey("shop", "/b"), 100)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer b.Abort()
+ a.Abort()
+ a.Abort()
+ if got, want := s.Stats().Reserved, int64(2*100+metaReserve); got != want {
+ t.Fatalf("Reserved = %d, want %d (b's alone)", got, want)
+ }
+}
+
+// TestReserveAndAbortConcurrently is not acceptance: it uses a fake FS. Run
+// with -race: counters must come back to zero.
+func TestReserveAndAbortConcurrently(t *testing.T) {
+ s, _, dir := fillStore(t)
+ var wg sync.WaitGroup
+ for g := 0; g < 8; g++ {
+ wg.Add(1)
+ go func(g int) {
+ defer wg.Done()
+ for i := 0; i < 50; i++ {
+ f, err := s.Reserve(testKey(fmt.Sprintf("app%d", g%3), fmt.Sprintf("/%d/%d", g, i)), 64)
+ if err != nil {
+ if !errors.Is(err, ErrBusy) {
+ t.Errorf("unexpected error: %v", err)
+ }
+ continue
+ }
+ if _, err := f.Write([]byte("body")); err != nil {
+ t.Errorf("write: %v", err)
+ }
+ f.Abort()
+ }
+ }(g)
+ }
+ wg.Wait()
+ if got := s.Stats().Reserved; got != 0 {
+ t.Fatalf("Reserved = %d after all aborted", got)
+ }
+ if got := listDir(t, dir); len(got) != 0 {
+ t.Fatalf("files left: %v", got)
+ }
+}
diff --git a/internal/assetcache/store.go b/internal/assetcache/store.go
index d31732cee..8fa99c913 100644
--- a/internal/assetcache/store.go
+++ b/internal/assetcache/store.go
@@ -45,11 +45,13 @@ func (e *entry) bytes() int64 { return e.meta.Size + e.meta.GzipSize }
type Store struct {
cfg Config
- 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
- reserved int64 // bytes promised to fills in flight
+ 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
+ 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
}
// Open creates the directory if needed and rebuilds the index from it.
@@ -66,6 +68,9 @@ func Open(cfg Config) (*Store, error) {
if cfg.Now == nil {
cfg.Now = time.Now
}
+ if cfg.FS == nil {
+ cfg.FS = Statfs
+ }
if err := os.MkdirAll(cfg.Dir, 0o700); err != nil {
return nil, fmt.Errorf("assetcache: %w", err)
}
@@ -73,6 +78,8 @@ func Open(cfg Config) (*Store, error) {
cfg: cfg,
entries: make(map[string]*entry),
apps: make(map[string]map[string]*entry),
+
+ fillsByApp: make(map[string]int),
}
if err := s.scan(); err != nil {
return nil, err