edge: EnableAssetCache and the five-minute asset sweep (asset cache plan 3 Task 7)
The edge's asset state becomes an atomic pointer, stored by EnableAssetCache from the agent's ready hook (the tunnel loop may already be serving). The sweep keeps a key only when the home's own catch or the home map answers for its host with the same account, app and generation, and drops nothing until both have given their first answer, so a restarted box keeps its warm store (design §7, drift D13).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+466
−19
internal/edge/asset_far_test.go+5 −5internal/edge/asset_local_test.go+3 −3internal/edge/assetarm.go+105 −0internal/edge/assetarm_test.go+336 −0internal/edge/assetcatch.go+11 −8internal/edge/edge.go+6 −3
diff --git a/internal/edge/asset_far_test.go b/internal/edge/asset_far_test.go| index 9291f1914..b6de8d36f 100644 |
| --- a/internal/edge/asset_far_test.go |
| +++ b/internal/edge/asset_far_test.go |
| @@ -109,7 +109,7 @@ func newFarEdge(t *testing.T, mk func(key []byte, m *homeMap) http.Handler, loca |
| tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { |
| return dialer.DialContext(ctx, network, net.JoinHostPort(eip, s.dialPort.Load().(string))) |
| } |
| - e.assets = &assetState{store: s.store, now: func() time.Time { return time.Now().Add(time.Duration(s.offset.Load())) }} |
| + e.assets.Store(&assetState{store: s.store, now: func() time.Time { return time.Now().Add(time.Duration(s.offset.Load())) }}) |
| e.EnableUsage(s.meter) |
| s.publish(t, time.Now()) |
| return s |
| @@ -181,7 +181,7 @@ func fillGate() (first func() bool, started chan struct{}, wait func(), release |
| } |
| func flightWaitersOf(e *Edge, id string) int { |
| - f := &e.assets.flight |
| + f := &e.assets.Load().flight |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| if c := f.m[id]; c != nil { |
| @@ -934,7 +934,7 @@ func TestBackhaulScrubsTheAssetVocabulary(t *testing.T) { |
| t.Run(tc.name, func(t *testing.T) { |
| s := newFarScene(t, vocabApp(laBody)) |
| if tc.unarmed { |
| - s.e.assets = nil |
| + s.e.assets.Store(nil) |
| } |
| s.home.set(func(h *farHome) { h.ack = !tc.noAck }) |
| front := httptest.NewServer(s.e) |
| @@ -1023,8 +1023,8 @@ func TestFarFillShedByTheFairShareIs429(t *testing.T) { |
| if n := s.rec.get().n; n != 0 { |
| t.Fatalf("the home saw %d requests, want none", n) |
| } |
| - if n := flightWaitersOf(s.e, s.key("/assets/app.js").ID()); n != 0 || len(s.e.assets.flight.m) != 0 { |
| - t.Fatalf("the refused fill left its flight open (%d waiters, %d flights)", n, len(s.e.assets.flight.m)) |
| + if n := flightWaitersOf(s.e, s.key("/assets/app.js").ID()); n != 0 || len(s.e.assets.Load().flight.m) != 0 { |
| + t.Fatalf("the refused fill left its flight open (%d waiters, %d flights)", n, len(s.e.assets.Load().flight.m)) |
| } |
| if v, _ := s.e.backhaulInflight.Load("betty"); v.(*atomic.Int64).Load() != 32 { |
| t.Fatalf("box count = %d, want the 32 held", v.(*atomic.Int64).Load()) |
diff --git a/internal/edge/asset_local_test.go b/internal/edge/asset_local_test.go| index be7cca56a..fc3c24c57 100644 |
| --- a/internal/edge/asset_local_test.go |
| +++ b/internal/edge/asset_local_test.go |
| @@ -159,7 +159,7 @@ func newLAScene(t *testing.T, h http.HandlerFunc, extra ...registry.Route) *laSc |
| s.local.set(laHost, laAssets()) |
| s.local.declare(laBuild, true) |
| s.store = openLAStore(t) |
| - e.assets = &assetState{store: s.store, local: s.local, now: time.Now} |
| + e.assets.Store(&assetState{store: s.store, local: s.local, now: time.Now}) |
| return s |
| } |
| @@ -349,7 +349,7 @@ func TestHibernatingRouteHitDoesNotWake(t *testing.T) { |
| t.Cleanup(e.probers.Stop) |
| local := &fakeLocalAssets{hosts: map[string]HostAssets{laHost: laAssets()}, builds: map[string]bool{laBuild: true}} |
| store := openLAStore(t) |
| - e.assets = &assetState{store: store, local: local, now: time.Now} |
| + e.assets.Store(&assetState{store: store, local: local, now: time.Now}) |
| s := &laScene{e: e} |
| wantCache(t, s.get(t, "/assets/app.js"), "miss") |
| @@ -1035,7 +1035,7 @@ func fillRequest(key []byte, host, path string, c assetFillClaims) (*http.Reques |
| } |
| func (s *laScene) flightWaiters(id string) int { |
| - f := &s.e.assets.flight |
| + f := &s.e.assets.Load().flight |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| if c := f.m[id]; c != nil { |
diff --git a/internal/edge/assetarm.go b/internal/edge/assetarm.go| new file mode 100644 |
| index 000000000..15b2522fb |
| --- /dev/null |
| +++ b/internal/edge/assetarm.go |
| @@ -0,0 +1,105 @@ |
| +package edge |
| + |
| +import ( |
| + "log" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/assetcache" |
| +) |
| + |
| +// assetSweepEvery is how often an armed edge sweeps its store (design §6, |
| +// plan 3 global constraints: every 5 minutes). |
| +const assetSweepEvery = 5 * time.Minute |
| + |
| +// EnableAssetCache arms the edge asset cache (design §10): s is the box's |
| +// disk store, local the home's own catch (internal/host's asset policy, the |
| +// same one its edges file writer fills, drift D12). It starts the sweep loop, |
| +// which runs for the life of the process. A nil s leaves the cache off and |
| +// changes nothing. Called once, from the agent's ready hook; a second call |
| +// replaces the first and stops its sweep. |
| +func (e *Edge) EnableAssetCache(s *assetcache.Store, local LocalAssets) { |
| + if s == nil { |
| + return |
| + } |
| + e.enableAssetCache(s, local, assetSweepEvery) |
| +} |
| + |
| +// enableAssetCache is EnableAssetCache with the sweep interval as a seam. |
| +func (e *Edge) enableAssetCache(s *assetcache.Store, local LocalAssets, every time.Duration) { |
| + done := make(chan struct{}) |
| + var once sync.Once |
| + st := &assetState{store: s, local: local, stop: func() { once.Do(func() { close(done) }) }} |
| + if old := e.assets.Swap(st); old != nil && old.stop != nil { |
| + old.stop() |
| + } |
| + go e.assetSweepLoop(st, every, done) |
| +} |
| + |
| +// stopAssetSweep stops the current sweep loop, if one runs. Tests only: in |
| +// production the loop lives as long as the process. |
| +func (e *Edge) stopAssetSweep() { |
| + if st := e.assets.Load(); st != nil && st.stop != nil { |
| + st.stop() |
| + } |
| +} |
| + |
| +func (e *Edge) assetSweepLoop(st *assetState, every time.Duration, done <-chan struct{}) { |
| + t := time.NewTicker(every) |
| + defer t.Stop() |
| + for { |
| + select { |
| + case <-done: |
| + return |
| + case <-t.C: |
| + if n := e.sweepAssets(st.clock()); n > 0 { |
| + log.Printf("edge: asset cache sweep dropped %d entries no longer current", n) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// assetsReadier is a LocalAssets that can say whether it holds its first |
| +// settled answer. internal/host's policy implements it; a LocalAssets that |
| +// does not is taken as ready. |
| +type assetsReadier interface { |
| + AssetsReady() bool |
| +} |
| + |
| +// sweepAssets drops every entry whose generation or owner is no longer |
| +// current (design §6): it keeps a key only when the home's own catch |
| +// (local.For) or the home map (AssetsFor) answers for its host with the same |
| +// account, app and generation. Everything else is garbage: a purged |
| +// generation, a host that changed owner, a host nothing catches for any |
| +// more, and a far host whose home has not been heard from within the hour. |
| +// It returns how many entries it dropped. |
| +// |
| +// Until both authorities have given their first answer (the home map's first |
| +// successful hosts read, the policy's first settled snapshot) a sweep drops |
| +// nothing: neither has said anything about a host yet, and a box that |
| +// restarts keeps its warm store for when they do (§7, drift D13). |
| +func (e *Edge) sweepAssets(now time.Time) int { |
| + st := e.assets.Load() |
| + if st == nil || st.store == nil { |
| + return 0 |
| + } |
| + m := e.homes.Load() |
| + if m != nil && !m.snapshot().read { |
| + return 0 |
| + } |
| + if r, ok := st.local.(assetsReadier); ok && !r.AssetsReady() { |
| + return 0 |
| + } |
| + same := func(a HostAssets, k assetcache.Key) bool { |
| + return a.Account == k.Account && a.App == k.App && a.Gen == k.Gen |
| + } |
| + return st.store.Retain(func(k assetcache.Key) bool { |
| + if st.local != nil { |
| + if a, ok := st.local.For(k.Host); ok && same(a, k) { |
| + return true |
| + } |
| + } |
| + a, ok := m.AssetsFor(k.Host, now) |
| + return ok && same(a, k) |
| + }) |
| +} |
diff --git a/internal/edge/assetarm_test.go b/internal/edge/assetarm_test.go| new file mode 100644 |
| index 000000000..696e2c105 |
| --- /dev/null |
| +++ b/internal/edge/assetarm_test.go |
| @@ -0,0 +1,336 @@ |
| +package edge |
| + |
| +import ( |
| + "fmt" |
| + "net/http" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/assetcache" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Arming and the sweep (edge asset cache design §6, §7, §10; plan 3 Task 7). |
| +// |
| +// Not acceptance: Task 5's and Task 6's scenes (one Edge, a real plan 2 |
| +// store, a fake policy or a fake home), armed through EnableAssetCache |
| +// rather than by setting the edge's state directly. Task 9 is the two-edge |
| +// acceptance gate. |
| + |
| +// armForTest arms e through the production entry point and stops its sweep |
| +// loop when the test ends. |
| +func armForTest(t *testing.T, e *Edge, s *assetcache.Store, local LocalAssets) { |
| + t.Helper() |
| + e.EnableAssetCache(s, local) |
| + t.Cleanup(e.stopAssetSweep) |
| +} |
| + |
| +// openStoreAt opens a store on dir, the way a restarted box reopens its |
| +// cache directory. |
| +func openStoreAt(t *testing.T, dir string) *assetcache.Store { |
| + t.Helper() |
| + st, err := assetcache.Open(assetcache.Config{Dir: dir, Budget: 1 << 30, FS: bigFS{}}) |
| + if err != nil { |
| + t.Fatalf("open store: %v", err) |
| + } |
| + return st |
| +} |
| + |
| +// publishOwner lands betty's edges file with laHost owned by acct/app under |
| +// gen, confirmed now. |
| +func (s *farScene) publishOwner(t *testing.T, acct, app, gen string) { |
| + t.Helper() |
| + putJSON(t, s.m.s, "control/edges/betty.json", fmt.Sprintf( |
| + `{"v":1,"box":"betty","eip":%q,"hosts":{%q:{"role":"home","account":%q,"app":%q,`+ |
| + `"assets":{"paths":["/assets/"],"gen":%q,"at":%d,"primary":%q}}}}`, |
| + s.eip, laHost, acct, app, gen, time.Now().Unix(), laHost)) |
| + refreshHomeMap(t, s.m) |
| +} |
| + |
| +func TestUnarmedEdgeForwardsAsToday(t *testing.T) { |
| + t.Run("a fresh edge is unarmed", func(t *testing.T) { |
| + e, err := New(openReg(t), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + if e.assets.Load() != nil { |
| + t.Fatal("New armed the asset cache") |
| + } |
| + }) |
| + t.Run("local", func(t *testing.T) { |
| + s := newLAScene(t, assetOK(laBody)) |
| + s.e.assets.Store(nil) // as New leaves it: no EnableAssetCache |
| + // The second request may be the shared LRU's (today's behaviour for |
| + // a cacheable response); neither is the asset cache's. |
| + for i := 0; i < 2; i++ { |
| + rec := s.get(t, "/assets/app.js") |
| + if rec.Code != http.StatusOK || rec.Body.String() != laBody { |
| + t.Fatalf("request %d = %d %q", i, rec.Code, rec.Body.String()) |
| + } |
| + if v := rec.Header().Values("Carlos-Cache"); len(v) > 0 { |
| + t.Fatalf("an unarmed edge answered Carlos-Cache %q", v) |
| + } |
| + if i == 0 && s.b.n.Load() != 1 { |
| + t.Fatalf("the first request was not proxied (the app saw %d)", s.b.n.Load()) |
| + } |
| + } |
| + if st := s.store.Stats(); st.Entries != 0 { |
| + t.Fatalf("an unarmed edge stored %+v", st) |
| + } |
| + }) |
| + t.Run("far", func(t *testing.T) { |
| + s := newFarScene(t, assetOK(laBody)) |
| + s.e.assets.Store(nil) |
| + for i := 0; i < 2; i++ { |
| + rec := s.get(t, "/assets/app.js") |
| + if rec.Code != http.StatusOK || rec.Body.String() != laBody { |
| + t.Fatalf("request %d = %d %q", i, rec.Code, rec.Body.String()) |
| + } |
| + if v := rec.Header().Values("Carlos-Cache"); len(v) > 0 { |
| + t.Fatalf("an unarmed edge answered Carlos-Cache %q", v) |
| + } |
| + } |
| + if seen := s.rec.get(); seen.n != 2 || seen.fill != "" || seen.hop != "1" { |
| + t.Fatalf("home saw n=%d fill=%q hop=%q, want two plain hops", seen.n, seen.fill, seen.hop) |
| + } |
| + if st := s.store.Stats(); st.Entries != 0 { |
| + t.Fatalf("an unarmed edge stored %+v", st) |
| + } |
| + }) |
| + t.Run("a nil store leaves it off", func(t *testing.T) { |
| + s := newFarScene(t, assetOK(laBody)) |
| + s.e.assets.Store(nil) |
| + s.e.EnableAssetCache(nil, nil) |
| + if s.e.assets.Load() != nil { |
| + t.Fatal("EnableAssetCache(nil) armed the edge") |
| + } |
| + rec := s.get(t, "/assets/app.js") |
| + if v := rec.Header().Values("Carlos-Cache"); len(v) > 0 || s.rec.get().fill != "" { |
| + t.Fatalf("Carlos-Cache %q, fill %q after a nil store", v, s.rec.get().fill) |
| + } |
| + }) |
| +} |
| + |
| +func TestSweepDropsAnOldGeneration(t *testing.T) { |
| + t.Run("local", func(t *testing.T) { |
| + s := newLAScene(t, assetOK(laBody)) |
| + armForTest(t, s.e, s.store, s.local) |
| + wantCache(t, s.get(t, "/assets/a.js"), "miss") |
| + wantCache(t, s.get(t, "/assets/b.js"), "miss") |
| + // A purge: the route row and the policy both move to a new token. |
| + purged := laAssets() |
| + purged.Gen = "fedcba9876543210" |
| + s.local.set(laHost, purged) |
| + s.setRouteGen(t, purged.Gen) |
| + wantCache(t, s.get(t, "/assets/a.js"), "miss") // stored under the new generation |
| + if n := s.e.sweepAssets(time.Now()); n != 2 { |
| + t.Fatalf("sweep dropped %d entries, want the 2 of the old generation", n) |
| + } |
| + old := assetcache.Key{Account: "abc", App: "shop", Gen: laGen, Host: laHost, Path: "/assets/a.js"} |
| + if _, ok := s.store.Get(old); ok { |
| + t.Fatal("an old-generation entry survived the sweep") |
| + } |
| + cur := old |
| + cur.Gen = purged.Gen |
| + if _, ok := s.store.Get(cur); !ok { |
| + t.Fatal("the sweep dropped the current generation's entry") |
| + } |
| + wantCache(t, s.get(t, "/assets/a.js"), "hit") |
| + }) |
| + t.Run("far", func(t *testing.T) { |
| + s := newFarScene(t, assetOK(laBody)) |
| + armForTest(t, s.e, s.store, nil) |
| + wantCache(t, s.get(t, "/assets/a.js"), "miss") |
| + if n := s.e.sweepAssets(time.Now()); n != 0 { |
| + t.Fatalf("sweep dropped %d current entries", n) |
| + } |
| + s.publishOwner(t, "abc", "shop", "fedcba9876543210") |
| + if n := s.e.sweepAssets(time.Now()); n != 1 { |
| + t.Fatalf("sweep dropped %d entries, want the old generation's 1", n) |
| + } |
| + if st := s.store.Stats(); st.Entries != 0 { |
| + t.Fatalf("after the sweep the store holds %+v", st) |
| + } |
| + }) |
| +} |
| + |
| +func TestSweepDropsAChangedOwner(t *testing.T) { |
| + t.Run("local app", func(t *testing.T) { |
| + s := newLAScene(t, assetOK(laBody)) |
| + armForTest(t, s.e, s.store, s.local) |
| + wantCache(t, s.get(t, "/assets/a.js"), "miss") |
| + moved := laAssets() |
| + moved.App = "other" |
| + s.local.set(laHost, moved) |
| + if n := s.e.sweepAssets(time.Now()); n != 1 { |
| + t.Fatalf("sweep dropped %d entries, want the old owner's 1", n) |
| + } |
| + }) |
| + t.Run("local account", func(t *testing.T) { |
| + s := newLAScene(t, assetOK(laBody)) |
| + armForTest(t, s.e, s.store, s.local) |
| + wantCache(t, s.get(t, "/assets/a.js"), "miss") |
| + moved := laAssets() |
| + moved.Account = "xyz" |
| + s.local.set(laHost, moved) |
| + if n := s.e.sweepAssets(time.Now()); n != 1 { |
| + t.Fatalf("sweep dropped %d entries, want the old owner's 1", n) |
| + } |
| + }) |
| + t.Run("far", func(t *testing.T) { |
| + s := newFarScene(t, assetOK(laBody)) |
| + armForTest(t, s.e, s.store, nil) |
| + wantCache(t, s.get(t, "/assets/a.js"), "miss") |
| + s.publishOwner(t, "xyz", "shop", laGen) |
| + if n := s.e.sweepAssets(time.Now()); n != 1 { |
| + t.Fatalf("sweep dropped %d entries, want the old owner's 1", n) |
| + } |
| + }) |
| +} |
| + |
| +// A host neither authority catches for any more (its home stopped |
| +// publishing, or the policy no longer catches it) is swept too. |
| +func TestSweepDropsAHostNothingCatches(t *testing.T) { |
| + t.Run("local", func(t *testing.T) { |
| + s := newLAScene(t, assetOK(laBody)) |
| + armForTest(t, s.e, s.store, s.local) |
| + wantCache(t, s.get(t, "/assets/a.js"), "miss") |
| + s.local.mu.Lock() |
| + delete(s.local.hosts, laHost) |
| + s.local.mu.Unlock() |
| + if n := s.e.sweepAssets(time.Now()); n != 1 { |
| + t.Fatalf("sweep dropped %d entries, want 1", n) |
| + } |
| + }) |
| + t.Run("far", func(t *testing.T) { |
| + s := newFarScene(t, assetOK(laBody)) |
| + armForTest(t, s.e, s.store, nil) |
| + wantCache(t, s.get(t, "/assets/a.js"), "miss") |
| + putJSON(t, s.m.s, "control/edges/betty.json", fmt.Sprintf(`{"v":1,"box":"betty","eip":%q,"hosts":{}}`, s.eip)) |
| + refreshHomeMap(t, s.m) |
| + if n := s.e.sweepAssets(time.Now()); n != 1 { |
| + t.Fatalf("sweep dropped %d entries, want 1", n) |
| + } |
| + }) |
| +} |
| + |
| +// notReadyLocal is a policy that has not taken its first settled snapshot. |
| +type notReadyLocal struct{ fakeLocalAssets } |
| + |
| +func (*notReadyLocal) AssetsReady() bool { return false } |
| + |
| +// Before either authority has given its first answer, nothing it would |
| +// answer for can be judged, so a sweep keeps the warm store whole (§7). |
| +func TestSweepKeepsEverythingBeforeTheFirstAnswers(t *testing.T) { |
| + t.Run("home map not read", func(t *testing.T) { |
| + s := newFarScene(t, assetOK(laBody)) |
| + armForTest(t, s.e, s.store, nil) |
| + wantCache(t, s.get(t, "/assets/a.js"), "miss") |
| + s.e.homes.Store(newHomeMap(s.m.s, "annie")) |
| + if n := s.e.sweepAssets(time.Now()); n != 0 { |
| + t.Fatalf("sweep dropped %d entries before the first hosts read", n) |
| + } |
| + if st := s.store.Stats(); st.Entries != 1 { |
| + t.Fatalf("store = %+v, want the entry kept", st) |
| + } |
| + }) |
| + t.Run("policy not settled", func(t *testing.T) { |
| + s := newLAScene(t, assetOK(laBody)) |
| + armForTest(t, s.e, s.store, s.local) |
| + wantCache(t, s.get(t, "/assets/a.js"), "miss") |
| + armForTest(t, s.e, s.store, ¬ReadyLocal{fakeLocalAssets{hosts: map[string]HostAssets{}, builds: map[string]bool{}}}) |
| + if n := s.e.sweepAssets(time.Now()); n != 0 { |
| + t.Fatalf("sweep dropped %d entries before the policy's first snapshot", n) |
| + } |
| + }) |
| +} |
| + |
| +// The loop EnableAssetCache starts sweeps on its own (every 5 minutes in |
| +// production; shortened here). |
| +func TestSweepLoopRunsOnItsTicker(t *testing.T) { |
| + s := newLAScene(t, assetOK(laBody)) |
| + s.e.enableAssetCache(s.store, s.local, 10*time.Millisecond) |
| + t.Cleanup(s.e.stopAssetSweep) |
| + wantCache(t, s.get(t, "/assets/a.js"), "miss") |
| + moved := laAssets() |
| + moved.Gen = "fedcba9876543210" |
| + s.local.set(laHost, moved) |
| + deadline := time.Now().Add(5 * time.Second) |
| + for s.store.Stats().Entries != 0 { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("the sweep loop never dropped the old generation: %+v", s.store.Stats()) |
| + } |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + if assetSweepEvery != 5*time.Minute { |
| + t.Fatalf("assetSweepEvery = %v, want the spec's 5 minutes", assetSweepEvery) |
| + } |
| +} |
| + |
| +// setRouteGen rewrites laHost's route row with gen and reloads the edge. |
| +func (s *laScene) setRouteGen(t *testing.T, gen string) { |
| + t.Helper() |
| + if err := s.reg.Upsert(registry.Route{Host: laHost, Kind: "instance", Addr: s.b.srv.Listener.Addr().String(), |
| + Status: "ready", Account: "abc", App: "shop", AssetGen: gen, Version: laBuild}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// D13 (§7 "after a restart"): a box restarts with a warm store and a fresh |
| +// home map. Until the map's first hosts read a far request gets no disk |
| +// answer and today's unresolved-host behaviour; after it the warm entry is |
| +// caught and an uncaught path forwards. |
| +func TestServesNothingBeforeTheFirstHomeMapRead(t *testing.T) { |
| + s := newFarScene(t, assetOK(laBody)) |
| + dir := filepath.Join(t.TempDir(), "asset-cache") |
| + armForTest(t, s.e, openStoreAt(t, dir), nil) |
| + wantCache(t, s.get(t, "/assets/app.js"), "miss") |
| + if n := s.rec.get().n; n != 1 { |
| + t.Fatalf("the home saw %d requests filling, want 1", n) |
| + } |
| + |
| + // The restart: the store reopened from its directory, the map empty. |
| + warm := openStoreAt(t, dir) |
| + if st := warm.Stats(); st.Entries != 1 { |
| + t.Fatalf("the reopened store holds %+v, want the warm entry", st) |
| + } |
| + fresh := newHomeMap(s.m.s, "annie") |
| + s.e.homes.Store(fresh) |
| + armForTest(t, s.e, warm, nil) |
| + |
| + for _, path := range []string{"/assets/app.js", "/index.html"} { |
| + rec := s.get(t, path) |
| + if rec.Code != http.StatusNotFound || rec.Header().Get("Carlos-Cache") != "" { |
| + t.Fatalf("%s before the first read = %d (Carlos-Cache %q), want the unknown-host 404", |
| + path, rec.Code, rec.Header().Get("Carlos-Cache")) |
| + } |
| + } |
| + if n := s.rec.get().n; n != 1 { |
| + t.Fatalf("the home saw %d requests before the first read, want none past the fill", n) |
| + } |
| + if n := s.e.sweepAssets(time.Now()); n != 0 { |
| + t.Fatalf("a sweep before the first read dropped %d entries", n) |
| + } |
| + |
| + refreshHomeMap(t, fresh) |
| + rec := s.get(t, "/assets/app.js") |
| + wantCache(t, rec, "hit") |
| + if rec.Body.String() != laBody { |
| + t.Fatalf("hit body = %q", rec.Body.String()) |
| + } |
| + if n := s.rec.get().n; n != 1 { |
| + t.Fatalf("the hit reached the home (%d requests)", n) |
| + } |
| + if rec := s.get(t, "/index.html"); rec.Code != http.StatusOK || rec.Header().Get("Carlos-Cache") != "" { |
| + t.Fatalf("an uncaught path after the read = %d (Carlos-Cache %q), want a plain backhaul", |
| + rec.Code, rec.Header().Get("Carlos-Cache")) |
| + } |
| + if seen := s.rec.get(); seen.n != 2 || seen.fill != "" { |
| + t.Fatalf("home saw n=%d fill=%q, want the uncaught path forwarded as a plain hop", seen.n, seen.fill) |
| + } |
| +} |
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go| index 3c78d4746..1861a59f5 100644 |
| --- a/internal/edge/assetcatch.go |
| +++ b/internal/edge/assetcatch.go |
| @@ -171,6 +171,9 @@ type assetState struct { |
| local LocalAssets |
| flight assetFlight |
| now func() time.Time |
| + // stop ends the sweep loop EnableAssetCache started for this state; nil |
| + // when none runs (a test that sets the state directly). |
| + stop func() |
| } |
| func (s *assetState) clock() time.Time { |
| @@ -238,7 +241,7 @@ func assetUpstreamMatches(a HostAssets, up upstream) bool { |
| // canonical-path and upstream checks come later: a request that fails them |
| // is still under a prefix, and is answered bypass. |
| func (e *Edge) localAssetCatch(r *http.Request, host string, up upstream) (HostAssets, bool) { |
| - st := e.assets |
| + st := e.assets.Load() |
| if st == nil || st.store == nil || st.local == nil { |
| return HostAssets{}, false |
| } |
| @@ -281,7 +284,7 @@ func (e *Edge) serveAssetLocal(w http.ResponseWriter, r *http.Request, host stri |
| e.assetForward(w, r, up, nil) |
| return true |
| } |
| - st := e.assets |
| + st := e.assets.Load() |
| k := assetKey(a, host, r.URL) |
| if ent, ok := st.store.Get(k); ok && serveAssetEntry(w, r, ent, st.clock(), "hit") == nil { |
| return true |
| @@ -354,7 +357,7 @@ func (e *Edge) serveAssetFillForHop(w http.ResponseWriter, r *http.Request, host |
| h.Del(assetAckHeader) |
| h.Del(assetExpiresHeader) |
| } |
| - st := e.assets |
| + st := e.assets.Load() |
| k := assetKey(a, host, r.URL) |
| serveHit := func(ent *assetcache.Entry) bool { |
| ack(w.Header(), ent.Meta.Expires.Unix()) |
| @@ -522,7 +525,7 @@ func (e *Edge) leadAssetFill(w http.ResponseWriter, r *http.Request, release fun |
| done(ent) |
| switch { |
| case ent != nil && assetBuffered(r): |
| - if serveAssetEntry(w, r, ent, e.assets.clock(), "miss") == nil { |
| + if serveAssetEntry(w, r, ent, e.assets.Load().clock(), "miss") == nil { |
| return |
| } |
| forward() |
| @@ -546,7 +549,7 @@ func (e *Edge) leadAssetFill(w http.ResponseWriter, r *http.Request, release fun |
| // route's Version otherwise, asked of the policy with the request hostname). |
| // The rest is runAssetFill. |
| func (e *Edge) fillFromApp(ctx context.Context, w http.ResponseWriter, r *http.Request, up upstream, k assetcache.Key, onHeader func(v assetVerdict, h http.Header)) (*assetcache.Entry, error) { |
| - st := e.assets |
| + st := e.assets.Load() |
| judge := func(code int, snap http.Header, reqTime, respTime time.Time) assetVerdict { |
| build := up.route.Version |
| if up.genManaged { |
| @@ -595,7 +598,7 @@ func (e *Edge) fillFromApp(ctx context.Context, w http.ResponseWriter, r *http.R |
| func (e *Edge) runAssetFill(ctx context.Context, w http.ResponseWriter, r *http.Request, k assetcache.Key, origin string, |
| judge func(code int, snap http.Header, reqTime, respTime time.Time) assetVerdict, |
| send func(http.ResponseWriter, *http.Request), onHeader func(v assetVerdict, h http.Header)) (*assetcache.Entry, error) { |
| - st := e.assets |
| + st := e.assets.Load() |
| upCtx, upCancel := context.WithCancel(context.WithValue(context.WithoutCancel(ctx), geoResultKey{}, geoip.Off())) |
| defer upCancel() |
| fw := &assetFillWriter{ |
| @@ -965,7 +968,7 @@ func stripAssetTrailers(resp *http.Response) { |
| // comes later: a request that fails it is still under a prefix, and is |
| // answered bypass. |
| func (e *Edge) farAssetCatch(r *http.Request, host string) (a HostAssets, eip, box string, key []byte, ok bool) { |
| - st := e.assets |
| + st := e.assets.Load() |
| if st == nil || st.store == nil { |
| return HostAssets{}, "", "", nil, false |
| } |
| @@ -1019,7 +1022,7 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string |
| forward() |
| return true |
| } |
| - st := e.assets |
| + st := e.assets.Load() |
| rt := registry.Route{Host: host, Account: a.Account, App: a.App, Kind: "instance"} |
| var n int64 |
| cw := &countingWriter{ResponseWriter: w, n: &n} |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index c1eb21a7b..ddc416a8e 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -250,9 +250,12 @@ type Edge struct { |
| // process); tests Stop it so probe goroutines don't outlive them. |
| probers *proberSet |
| // assets, when non-nil, is the armed edge asset cache (assetcatch.go): |
| - // the disk store, the home's own catch and the fill coalescer. Nil (every |
| - // box until Task 7's arming) keeps every request on today's path. |
| - assets *assetState |
| + // the disk store, the home's own catch and the fill coalescer. Nil (a box |
| + // without CARLOS_ASSET_CACHE=1) keeps every request on today's path. |
| + // Stored by EnableAssetCache (assetarm.go) from the agent's ready hook, |
| + // which runs while the tunnel loop may already be serving, hence the |
| + // atomic. Once armed it is never set back to nil. |
| + assets atomic.Pointer[assetState] |
| // gzipOn is the CARLOS_EDGE_GZIP kill switch, read once in New. When |
| // false, ServeHTTP never constructs a gzipWriter and the writer stack is |
| // byte-for-byte what it was before compression existed (compress.go). |