assetcache: keys, metadata and Open
The first piece of the edge asset cache's bounded disk store. Key.ID is a length-prefixed sha256, Meta is a JSON file that tolerates unknown fields, and Open rebuilds the index from the .meta files after removing temporaries, orphan and superseded bodies, and unparseable or incomplete entries.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
5 files changed,
+561
−0
internal/assetcache/fs.go+9 −0internal/assetcache/key.go+31 −0internal/assetcache/meta.go+62 −0internal/assetcache/store.go+187 −0internal/assetcache/store_test.go+272 −0
diff --git a/internal/assetcache/fs.go b/internal/assetcache/fs.go| new file mode 100644 |
| index 000000000..34de260a3 |
| --- /dev/null |
| +++ b/internal/assetcache/fs.go |
| @@ -0,0 +1,9 @@ |
| +package assetcache |
| + |
| +// FS is the store's view of the filesystem's free space. The Linux |
| +// implementation is statfs; tests may supply a fake. |
| +type FS interface { |
| + // Space reports the size of the filesystem holding dir and the bytes |
| + // available to an unprivileged writer. |
| + Space(dir string) (total, free uint64, err error) |
| +} |
diff --git a/internal/assetcache/key.go b/internal/assetcache/key.go| new file mode 100644 |
| index 000000000..111f017e8 |
| --- /dev/null |
| +++ b/internal/assetcache/key.go |
| @@ -0,0 +1,31 @@ |
| +package assetcache |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/binary" |
| + "encoding/hex" |
| +) |
| + |
| +// Key identifies one cached response: which app generation served it, on |
| +// which host, for which path and query. |
| +type Key struct { |
| + Account, App, Gen, Host, Path, RawQuery string |
| +} |
| + |
| +// ID is the hex sha256 over the six fields. Each field is written with its |
| +// length first, so no two distinct keys hash the same input. |
| +func (k Key) ID() string { |
| + h := sha256.New() |
| + var n [8]byte |
| + for _, f := range [...]string{k.Account, k.App, k.Gen, k.Host, k.Path, k.RawQuery} { |
| + binary.BigEndian.PutUint64(n[:], uint64(len(f))) |
| + h.Write(n[:]) |
| + h.Write([]byte(f)) |
| + } |
| + return hex.EncodeToString(h.Sum(nil)) |
| +} |
| + |
| +// AppScope names the app this key belongs to, for per-app accounting. |
| +func (k Key) AppScope() string { |
| + return k.Account + "/" + k.App |
| +} |
diff --git a/internal/assetcache/meta.go b/internal/assetcache/meta.go| new file mode 100644 |
| index 000000000..6a369abd9 |
| --- /dev/null |
| +++ b/internal/assetcache/meta.go |
| @@ -0,0 +1,62 @@ |
| +package assetcache |
| + |
| +import ( |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "time" |
| +) |
| + |
| +// Meta is what the store keeps beside an entry's body files. GzipSize is |
| +// zero when there is no gzip copy. Version names the body files, so a |
| +// commit never overwrites bytes an older Meta still points at. |
| +type Meta struct { |
| + Key Key |
| + Version string |
| + Header http.Header |
| + Lifetime time.Duration |
| + Expires time.Time |
| + StoredAt time.Time |
| + Size int64 |
| + GzipSize int64 |
| +} |
| + |
| +func encodeMeta(m Meta) ([]byte, error) { |
| + return json.Marshal(m) |
| +} |
| + |
| +// decodeMeta parses a .meta file. Fields it does not know are ignored, so a |
| +// file written by a newer binary still loads. |
| +func decodeMeta(raw []byte) (Meta, error) { |
| + var m Meta |
| + if err := json.Unmarshal(raw, &m); err != nil { |
| + return Meta{}, err |
| + } |
| + if !validVersion(m.Version) { |
| + return Meta{}, fmt.Errorf("version %q is not a file name part", m.Version) |
| + } |
| + if m.Size < 0 || m.GzipSize < 0 { |
| + return Meta{}, fmt.Errorf("negative size") |
| + } |
| + return m, nil |
| +} |
| + |
| +// validVersion accepts the short alphanumeric tokens the store draws, and |
| +// nothing that could change which file a name refers to. |
| +func validVersion(v string) bool { |
| + if v == "" || len(v) > 64 { |
| + return false |
| + } |
| + for _, c := range v { |
| + switch { |
| + case c >= '0' && c <= '9', c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z': |
| + default: |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func metaName(id string) string { return id + ".meta" } |
| +func bodyName(id, version string) string { return id + "." + version + ".body" } |
| +func gzipName(id, version string) string { return id + "." + version + ".gz" } |
diff --git a/internal/assetcache/store.go b/internal/assetcache/store.go| new file mode 100644 |
| index 000000000..6293da5ad |
| --- /dev/null |
| +++ b/internal/assetcache/store.go |
| @@ -0,0 +1,187 @@ |
| +// Package assetcache is a bounded disk store for cached asset responses. |
| +// |
| +// Each entry is a <id>.meta file (JSON) naming its versioned body files, |
| +// <id>.<v>.body and optionally <id>.<v>.gz. The index lives in memory and |
| +// is rebuilt from the .meta files by Open. |
| +package assetcache |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// Config configures a Store. |
| +type Config struct { |
| + Dir string // the cache directory; created 0700 |
| + Budget int64 // bytes of bodies 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 |
| + Bytes int64 |
| + Reserved int64 |
| + Apps int |
| +} |
| + |
| +// entry is one indexed cache entry. |
| +type entry struct { |
| + id string |
| + meta Meta |
| +} |
| + |
| +// bytes is the disk the entry's body files hold. |
| +func (e *entry) bytes() int64 { return e.meta.Size + e.meta.GzipSize } |
| + |
| +// Store is a bounded disk cache over one directory. |
| +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 |
| +} |
| + |
| +// Open creates the directory if needed and rebuilds the index from it. |
| +// It removes whatever a crash can leave behind: temporaries, body files no |
| +// parsed .meta names (orphans and superseded versions), and a .meta that |
| +// does not parse or whose files are incomplete, together with its files. |
| +func Open(cfg Config) (*Store, error) { |
| + if cfg.Dir == "" { |
| + return nil, errors.New("assetcache: no directory") |
| + } |
| + if cfg.Budget <= 0 { |
| + return nil, errors.New("assetcache: budget must be positive") |
| + } |
| + if cfg.Now == nil { |
| + cfg.Now = time.Now |
| + } |
| + if err := os.MkdirAll(cfg.Dir, 0o700); err != nil { |
| + return nil, fmt.Errorf("assetcache: %w", err) |
| + } |
| + s := &Store{ |
| + cfg: cfg, |
| + entries: make(map[string]*entry), |
| + apps: make(map[string]map[string]*entry), |
| + } |
| + if err := s.scan(); err != nil { |
| + return nil, err |
| + } |
| + return s, nil |
| +} |
| + |
| +func (s *Store) scan() error { |
| + ents, err := os.ReadDir(s.cfg.Dir) |
| + if err != nil { |
| + return fmt.Errorf("assetcache: %w", err) |
| + } |
| + var metas, files []string |
| + for _, de := range ents { |
| + if de.IsDir() { |
| + continue |
| + } |
| + name := de.Name() |
| + switch { |
| + case strings.Contains(name, ".tmp-"): |
| + if err := s.remove(name); err != nil { |
| + return err |
| + } |
| + case strings.HasSuffix(name, ".meta"): |
| + metas = append(metas, name) |
| + case strings.HasSuffix(name, ".body"), strings.HasSuffix(name, ".gz"): |
| + files = append(files, name) |
| + } |
| + } |
| + |
| + keep := make(map[string]bool) // body file names a parsed meta names |
| + for _, name := range metas { |
| + id := strings.TrimSuffix(name, ".meta") |
| + m, ok := s.loadMeta(id) |
| + if !ok { |
| + if err := s.remove(name); err != nil { |
| + return err |
| + } |
| + continue |
| + } |
| + keep[bodyName(id, m.Version)] = true |
| + if m.GzipSize > 0 { |
| + keep[gzipName(id, m.Version)] = true |
| + } |
| + s.index(&entry{id: id, meta: m}) |
| + } |
| + for _, name := range files { |
| + if !keep[name] { |
| + if err := s.remove(name); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// loadMeta reads and checks <id>.meta. It reports false for a file that |
| +// does not parse, belongs to another key, or lacks a body file it names. |
| +func (s *Store) loadMeta(id string) (Meta, bool) { |
| + raw, err := os.ReadFile(filepath.Join(s.cfg.Dir, metaName(id))) |
| + if err != nil { |
| + return Meta{}, false |
| + } |
| + m, err := decodeMeta(raw) |
| + if err != nil || m.Key.ID() != id { |
| + return Meta{}, false |
| + } |
| + names := []string{bodyName(id, m.Version)} |
| + if m.GzipSize > 0 { |
| + names = append(names, gzipName(id, m.Version)) |
| + } |
| + for _, n := range names { |
| + fi, err := os.Stat(filepath.Join(s.cfg.Dir, n)) |
| + if err != nil || !fi.Mode().IsRegular() { |
| + return Meta{}, false |
| + } |
| + } |
| + return m, true |
| +} |
| + |
| +// remove deletes one file of the store's directory by name. |
| +func (s *Store) remove(name string) error { |
| + if err := os.Remove(filepath.Join(s.cfg.Dir, name)); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return fmt.Errorf("assetcache: %w", err) |
| + } |
| + return nil |
| +} |
| + |
| +// index adds e to the in-memory index. 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() |
| + app := s.apps[scope] |
| + if app == nil { |
| + app = make(map[string]*entry) |
| + s.apps[scope] = app |
| + } |
| + app[e.id] = e |
| + s.used += e.bytes() |
| +} |
| + |
| +// Stats reports the store's current accounting. |
| +func (s *Store) Stats() Stats { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return Stats{ |
| + Entries: len(s.entries), |
| + Bytes: s.used, |
| + Reserved: s.reserved, |
| + Apps: len(s.apps), |
| + } |
| +} |
diff --git a/internal/assetcache/store_test.go b/internal/assetcache/store_test.go| new file mode 100644 |
| index 000000000..9c6f8581e |
| --- /dev/null |
| +++ b/internal/assetcache/store_test.go |
| @@ -0,0 +1,272 @@ |
| +package assetcache |
| + |
| +import ( |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "sort" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +var testNow = time.Date(2026, 10, 24, 12, 0, 0, 0, time.UTC) |
| + |
| +func testKey(app, path string) Key { |
| + return Key{Account: "abc", App: app, Gen: "g1", Host: "shop.example.com", Path: path} |
| +} |
| + |
| +func testConfig(dir string) Config { |
| + return Config{Dir: dir, Budget: 1 << 20, Now: func() time.Time { return testNow }} |
| +} |
| + |
| +// writeEntry writes an entry's files by hand in the documented layout: |
| +// <id>.meta plus <id>.<v>.body and, when gz is non-empty, <id>.<v>.gz. |
| +func writeEntry(t *testing.T, dir string, k Key, version string, body, gz []byte) Meta { |
| + t.Helper() |
| + m := Meta{ |
| + Key: k, |
| + Version: version, |
| + Header: http.Header{"Content-Type": {"text/css"}}, |
| + Lifetime: time.Hour, |
| + Expires: testNow.Add(time.Hour), |
| + StoredAt: testNow, |
| + Size: int64(len(body)), |
| + GzipSize: int64(len(gz)), |
| + } |
| + writeVersionFiles(t, dir, k.ID(), version, body, gz) |
| + raw, err := encodeMeta(m) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + writeFile(t, filepath.Join(dir, k.ID()+".meta"), raw) |
| + return m |
| +} |
| + |
| +func writeVersionFiles(t *testing.T, dir, id, version string, body, gz []byte) { |
| + t.Helper() |
| + writeFile(t, filepath.Join(dir, id+"."+version+".body"), body) |
| + if len(gz) > 0 { |
| + writeFile(t, filepath.Join(dir, id+"."+version+".gz"), gz) |
| + } |
| +} |
| + |
| +func writeFile(t *testing.T, path string, data []byte) { |
| + t.Helper() |
| + if err := os.WriteFile(path, data, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func listDir(t *testing.T, dir string) []string { |
| + t.Helper() |
| + ents, err := os.ReadDir(dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var names []string |
| + for _, e := range ents { |
| + names = append(names, e.Name()) |
| + } |
| + sort.Strings(names) |
| + return names |
| +} |
| + |
| +func sameNames(t *testing.T, got, want []string) { |
| + t.Helper() |
| + sort.Strings(want) |
| + if strings.Join(got, "\n") != strings.Join(want, "\n") { |
| + t.Fatalf("dir after Open = %v, want %v", got, want) |
| + } |
| +} |
| + |
| +func openStore(t *testing.T, dir string) *Store { |
| + t.Helper() |
| + s, err := Open(testConfig(dir)) |
| + if err != nil { |
| + t.Fatalf("Open: %v", err) |
| + } |
| + return s |
| +} |
| + |
| +func TestKeyIDIsStableAndDistinct(t *testing.T) { |
| + a := Key{Account: "abc", App: "shop", Gen: "g1", Host: "shop.example.com", Path: "/a.css", RawQuery: "v=1"} |
| + if a.ID() != a.ID() { |
| + t.Fatal("same key gave two ids") |
| + } |
| + if len(a.ID()) != 64 || strings.Trim(a.ID(), "0123456789abcdef") != "" { |
| + t.Fatalf("id %q is not 64 hex characters", a.ID()) |
| + } |
| + moved := a |
| + moved.Path, moved.RawQuery = "/a.cssv", "=1" |
| + if a.ID() == moved.ID() { |
| + t.Fatal("moving a character between Path and RawQuery kept the id") |
| + } |
| + moved = a |
| + moved.App, moved.Gen = "shop1", "g" |
| + if a.ID() == moved.ID() { |
| + t.Fatal("moving a character between App and Gen kept the id") |
| + } |
| + if got := a.AppScope(); got != "abc/shop" { |
| + t.Fatalf("AppScope = %q, want abc/shop", got) |
| + } |
| +} |
| + |
| +func TestOpenCreatesTheDirectory(t *testing.T) { |
| + dir := filepath.Join(t.TempDir(), "nested", "cache") |
| + s := openStore(t, dir) |
| + fi, err := os.Stat(dir) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !fi.IsDir() { |
| + t.Fatal("Dir is not a directory") |
| + } |
| + if perm := fi.Mode().Perm(); perm != 0o700 { |
| + t.Fatalf("Dir mode = %o, want 700", perm) |
| + } |
| + if st := s.Stats(); st != (Stats{}) { |
| + t.Fatalf("empty store Stats = %+v", st) |
| + } |
| +} |
| + |
| +func TestOpenRejectsBadConfig(t *testing.T) { |
| + if _, err := Open(Config{Budget: 1}); err == nil { |
| + t.Fatal("Open with no Dir succeeded") |
| + } |
| + if _, err := Open(Config{Dir: t.TempDir()}); err == nil { |
| + t.Fatal("Open with no Budget succeeded") |
| + } |
| +} |
| + |
| +func TestOpenRemovesOrphanBodiesAndTemporaries(t *testing.T) { |
| + dir := t.TempDir() |
| + kept := testKey("shop", "/kept.css") |
| + writeEntry(t, dir, kept, "a", []byte("body"), []byte("gz")) |
| + |
| + // A crash after the bodies were written but before the meta rename. |
| + orphan := testKey("shop", "/orphan.css") |
| + writeVersionFiles(t, dir, orphan.ID(), "a", []byte("orphan body"), []byte("orphan gz")) |
| + // Temporaries from an interrupted fill and an interrupted meta write. |
| + writeFile(t, filepath.Join(dir, orphan.ID()+".a.body.tmp-123"), []byte("partial")) |
| + writeFile(t, filepath.Join(dir, kept.ID()+".meta.tmp-456"), []byte("{")) |
| + // A file that is not ours stays. |
| + writeFile(t, filepath.Join(dir, "README"), []byte("hi")) |
| + |
| + 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")) { |
| + t.Fatalf("Stats = %+v, want 1 entry of 6 bytes", st) |
| + } |
| +} |
| + |
| +func TestOpenKeepsMetaWithUnknownFields(t *testing.T) { |
| + dir := t.TempDir() |
| + k := testKey("shop", "/new.css") |
| + m := Meta{Key: k, Version: "a", Lifetime: time.Hour, Expires: testNow.Add(time.Hour), StoredAt: testNow, Size: 4} |
| + raw, err := encodeMeta(m) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // Splice an unknown top-level field and an unknown nested one into the |
| + // JSON, as a newer binary would have written. |
| + s := string(raw) |
| + s = strings.Replace(s, `"Version"`, `"FromTheFuture":{"x":[1,2,3]},"Version"`, 1) |
| + s = strings.Replace(s, `"Account"`, `"Region":"eu","Account"`, 1) |
| + if !strings.Contains(s, "FromTheFuture") || !strings.Contains(s, "Region") { |
| + t.Fatalf("could not splice unknown fields into %s", raw) |
| + } |
| + writeFile(t, filepath.Join(dir, k.ID()+".meta"), []byte(s)) |
| + writeVersionFiles(t, dir, k.ID(), "a", []byte("body"), nil) |
| + |
| + st := openStore(t, dir).Stats() |
| + if st.Entries != 1 || st.Bytes != 4 { |
| + t.Fatalf("Stats = %+v, want the entry kept", st) |
| + } |
| + sameNames(t, listDir(t, dir), []string{k.ID() + ".meta", k.ID() + ".a.body"}) |
| +} |
| + |
| +func TestOpenDropsUnparseableMeta(t *testing.T) { |
| + dir := t.TempDir() |
| + good := testKey("shop", "/good.css") |
| + writeEntry(t, dir, good, "a", []byte("good"), nil) |
| + |
| + bad := testKey("shop", "/bad.css") |
| + writeVersionFiles(t, dir, bad.ID(), "a", []byte("bad body"), []byte("bad gz")) |
| + writeFile(t, filepath.Join(dir, bad.ID()+".meta"), []byte(`{"Key": {"Acc`)) |
| + |
| + // A meta that parses but names a different key than its file name |
| + // has been moved or tampered with, so it is dropped too. |
| + moved := testKey("shop", "/moved.css") |
| + other := testKey("blog", "/other.css") |
| + m := writeEntry(t, dir, other, "a", []byte("other"), nil) |
| + raw, err := encodeMeta(m) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + writeFile(t, filepath.Join(dir, moved.ID()+".meta"), raw) |
| + writeVersionFiles(t, dir, moved.ID(), "a", []byte("moved"), nil) |
| + |
| + // A meta whose version would escape the directory is dropped too. |
| + evil := testKey("shop", "/evil.css") |
| + raw, err = encodeMeta(Meta{Key: evil, Version: "../x", Size: 1}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + 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")) { |
| + t.Fatalf("Stats = %+v, want only the good and other entries", st) |
| + } |
| + sameNames(t, listDir(t, dir), []string{ |
| + good.ID() + ".a.body", good.ID() + ".meta", |
| + other.ID() + ".a.body", other.ID() + ".meta", |
| + }) |
| +} |
| + |
| +func TestOpenDropsEntryWhoseBodyIsMissing(t *testing.T) { |
| + dir := t.TempDir() |
| + k := testKey("shop", "/half.css") |
| + writeEntry(t, dir, k, "a", []byte("body"), []byte("gz")) |
| + if err := os.Remove(filepath.Join(dir, k.ID()+".a.gz")); err != nil { |
| + t.Fatal(err) |
| + } |
| + s := openStore(t, dir) |
| + if st := s.Stats(); st != (Stats{}) { |
| + t.Fatalf("Stats = %+v, want the half entry dropped", st) |
| + } |
| + sameNames(t, listDir(t, dir), nil) |
| +} |
| + |
| +func TestOpenIndexesExistingEntries(t *testing.T) { |
| + dir := t.TempDir() |
| + writeEntry(t, dir, testKey("shop", "/a.css"), "a", []byte("aaaa"), []byte("aa")) |
| + writeEntry(t, dir, testKey("shop", "/b.js"), "b", []byte("bbbbbb"), nil) |
| + writeEntry(t, dir, testKey("blog", "/c.png"), "c", []byte("cc"), nil) |
| + |
| + s := openStore(t, dir) |
| + st := s.Stats() |
| + want := Stats{Entries: 3, Bytes: 4 + 2 + 6 + 2, Reserved: 0, Apps: 2} |
| + if st != want { |
| + t.Fatalf("Stats = %+v, want %+v", st, want) |
| + } |
| + if n := len(listDir(t, dir)); n != 3+4 { |
| + t.Fatalf("%d files after Open, want 7", n) |
| + } |
| +} |
| + |
| +func TestOpenDeletesSupersededVersions(t *testing.T) { |
| + dir := t.TempDir() |
| + k := testKey("shop", "/a.css") |
| + // Crash after the meta rename but before the old version was deleted. |
| + writeVersionFiles(t, dir, k.ID(), "a", []byte("old body"), []byte("old gz")) |
| + writeEntry(t, dir, k, "b", []byte("new"), []byte("n")) |
| + |
| + 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) |
| + } |
| +} |