host: arm the edge asset cache with the edges file loop's own policy (asset cache plan 3 Task 7)
The agent builds the box's one asset policy before runDuties and hands it to edgesFileLoop (which binds its manifest cache to the loop's store) and, in the ready hook, to the edge with a store opened at $CARLOS_DATA_DIR/asset-cache under CARLOS_ASSET_CACHE_MAX or the default budget (drift D12). A Statfs or Open error logs and leaves the cache off. AssetsReady tells the edge's sweep the policy has its first snapshot.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+289
−11
internal/host/agent.go+14 −1internal/host/assetarm.go+57 −0internal/host/assetarm_test.go+183 −0internal/host/assetpolicy.go+20 −0internal/host/edgesfile.go+15 −10
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 4f78e06ed..9eaa5fc82 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -177,6 +177,7 @@ import ( |
| "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/apperr" |
| "github.com/carlosframework/platform/internal/applog" |
| + "github.com/carlosframework/platform/internal/assetcache" |
| "github.com/carlosframework/platform/internal/caps" |
| "github.com/carlosframework/platform/internal/cgroup" |
| "github.com/carlosframework/platform/internal/controlsock" |
| @@ -721,6 +722,12 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // Certificate issuance must not wait for instance recovery. |
| stopHousekeeper = startHousekeeper() |
| } |
| + // The box's one asset policy (edge asset cache design §4.1, §10; drift |
| + // D12): nil unless CARLOS_ASSET_CACHE=1. The edges file loop fills its |
| + // snapshots and publishes from it; the edge's own catch and sweep answer |
| + // from the same snapshots, armed in the ready hook below. Built here, |
| + // before either goroutine starts, so both are handed the one pointer. |
| + boxAssets := armAssetPolicy(os.Getenv, reg, boxAssetAuthority, nil, servingBuildOf(svc)) |
| dutiesDone := make(chan struct{}) |
| runDuties := func() { |
| defer close(dutiesDone) |
| @@ -833,7 +840,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| } |
| go retentionLoop(reg, collectBuildStates) |
| go registrySnapshotLoop(reg) |
| - go edgesFileLoop(reg, servingBuildOf(svc)) |
| + go edgesFileLoop(reg, boxAssets) |
| // Region HA enrollment evidence (spec 1 §5.1): once, at start, and only |
| // with CARLOS_REGION_HA on. See boxrecord.go. |
| go boxRecordLoop() |
| @@ -981,6 +988,12 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| e.EnableRequestRecords(rec) |
| go reqrecLoop(rec, time.NewTicker(time.Minute).C) |
| } |
| + // The edge asset cache (design §7, §10), last, so the meter, the rate |
| + // ceiling and the plan throttle are in place before it answers |
| + // anything: with CARLOS_ASSET_CACHE=1, the disk store under the data |
| + // dir and the policy the edges file loop fills. Unarmed, or when the |
| + // store will not open, the edge forwards as today. |
| + armEdgeAssetCache(os.Getenv, dataDir(), assetcache.Statfs, boxAssets, e.EnableAssetCache) |
| }, edgeOpts...) |
| var seedErr error |
diff --git a/internal/host/assetarm.go b/internal/host/assetarm.go| new file mode 100644 |
| index 000000000..a26777876 |
| --- /dev/null |
| +++ b/internal/host/assetarm.go |
| @@ -0,0 +1,57 @@ |
| +package host |
| + |
| +import ( |
| + "log" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/assetcache" |
| + "github.com/carlosframework/platform/internal/edge" |
| +) |
| + |
| +// assetCacheDirName is the store's directory under $CARLOS_DATA_DIR (design |
| +// §7). |
| +const assetCacheDirName = "asset-cache" |
| + |
| +// assetCacheBudget is the store's budget (design §7): CARLOS_ASSET_CACHE_MAX |
| +// bytes when it is set to a positive integer, else the default for a data |
| +// filesystem of total bytes (the smaller of 4 GiB and a tenth of it). |
| +func assetCacheBudget(getenv func(string) string, total uint64) int64 { |
| + if v := strings.TrimSpace(getenv("CARLOS_ASSET_CACHE_MAX")); v != "" { |
| + if n, err := strconv.ParseInt(v, 10, 64); err == nil && n > 0 { |
| + return n |
| + } |
| + } |
| + return assetcache.DefaultBudget(total) |
| +} |
| + |
| +// armEdgeAssetCache is the ready hook's arming (design §10): on a box with |
| +// CARLOS_ASSET_CACHE=1 it opens the store at dataDir/asset-cache and hands |
| +// enable (the edge's EnableAssetCache) the store and policy, the one policy |
| +// the edges file loop fills (drift D12). Unarmed, or with no policy, it does |
| +// nothing and the edge forwards as today. A Statfs or Open error is logged |
| +// and leaves the cache off; the box still publishes its assets blocks, and |
| +// fills sent to it are then answered as ordinary hops. It returns the store |
| +// it handed over, or nil. |
| +func armEdgeAssetCache(getenv func(string) string, dataDir string, fs assetcache.FS, policy *assetPolicy, enable func(*assetcache.Store, edge.LocalAssets)) *assetcache.Store { |
| + if !assetCacheArmed(getenv) || policy == nil { |
| + return nil |
| + } |
| + dir := filepath.Join(dataDir, assetCacheDirName) |
| + total, _, err := fs.Space(dataDir) |
| + if err != nil { |
| + log.Printf("agent: asset cache off: free space of %s: %v", dataDir, err) |
| + return nil |
| + } |
| + budget := assetCacheBudget(getenv, total) |
| + s, err := assetcache.Open(assetcache.Config{Dir: dir, Budget: budget, FS: fs}) |
| + if err != nil { |
| + log.Printf("agent: asset cache off: %v", err) |
| + return nil |
| + } |
| + st := s.Stats() |
| + log.Printf("agent: asset cache armed at %s (budget %d bytes, %d entries on disk)", dir, budget, st.Entries) |
| + enable(s, policy) |
| + return s |
| +} |
diff --git a/internal/host/assetarm_test.go b/internal/host/assetarm_test.go| new file mode 100644 |
| index 000000000..7d309f057 |
| --- /dev/null |
| +++ b/internal/host/assetarm_test.go |
| @@ -0,0 +1,183 @@ |
| +package host |
| + |
| +import ( |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/assetcache" |
| + "github.com/carlosframework/platform/internal/edge" |
| +) |
| + |
| +// Arming the edge asset cache (design §7, §10; plan 3 Task 7). |
| +// |
| +// Not acceptance: the store is a real plan 2 store on a temporary data |
| +// directory with a fake free-space source, and the edge is a recorder of |
| +// what EnableAssetCache was handed. The tests use t.Setenv, so none is |
| +// parallel. |
| + |
| +// spaceFS reports a fixed filesystem size, or an error. |
| +type spaceFS struct { |
| + total, free uint64 |
| + err error |
| +} |
| + |
| +func (f spaceFS) Space(string) (uint64, uint64, error) { return f.total, f.free, f.err } |
| + |
| +// enableRecorder stands in for (*edge.Edge).EnableAssetCache. |
| +type enableRecorder struct { |
| + calls int |
| + store *assetcache.Store |
| + local edge.LocalAssets |
| +} |
| + |
| +func (r *enableRecorder) enable(s *assetcache.Store, local edge.LocalAssets) { |
| + r.calls++ |
| + r.store, r.local = s, local |
| +} |
| + |
| +// armFromEnv is the ready hook's arming, as the agent runs it: the policy |
| +// from armAssetPolicy over the process environment, the store under |
| +// dataDir(). |
| +func armFromEnv(t *testing.T, w *assetWorld, fs assetcache.FS) (*assetPolicy, *enableRecorder) { |
| + t.Helper() |
| + p := armAssetPolicy(os.Getenv, w.reg, w.auth, w.cache, w.servingBuild) |
| + rec := &enableRecorder{} |
| + armEdgeAssetCache(os.Getenv, dataDir(), fs, p, rec.enable) |
| + return p, rec |
| +} |
| + |
| +var roomyFS = spaceFS{total: 100 << 30, free: 50 << 30} |
| + |
| +func TestAssetCacheArmingReadsTheEnv(t *testing.T) { |
| + for _, v := range []string{"", "0", "true", "yes", " 1", "1 "} { |
| + data := t.TempDir() |
| + t.Setenv("CARLOS_DATA_DIR", data) |
| + t.Setenv("CARLOS_ASSET_CACHE", v) |
| + p, rec := armFromEnv(t, newAssetWorld(t), roomyFS) |
| + if p != nil || rec.calls != 0 { |
| + t.Fatalf("CARLOS_ASSET_CACHE=%q: policy %v, %d EnableAssetCache call(s), want none", v, p != nil, rec.calls) |
| + } |
| + if _, err := os.Stat(filepath.Join(data, "asset-cache")); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("CARLOS_ASSET_CACHE=%q: the cache directory exists (%v)", v, err) |
| + } |
| + } |
| + |
| + data := t.TempDir() |
| + t.Setenv("CARLOS_DATA_DIR", data) |
| + t.Setenv("CARLOS_ASSET_CACHE", "1") |
| + p, rec := armFromEnv(t, newAssetWorld(t), roomyFS) |
| + if p == nil || rec.calls != 1 || rec.store == nil { |
| + t.Fatalf("armed: policy %v, %d call(s), store %v; want one call with a store", p != nil, rec.calls, rec.store != nil) |
| + } |
| + if got, ok := rec.local.(*assetPolicy); !ok || got != p { |
| + t.Fatalf("the edge was handed %T %p, want the policy itself %p (drift D12)", rec.local, rec.local, p) |
| + } |
| + fi, err := os.Stat(filepath.Join(data, "asset-cache")) |
| + if err != nil || !fi.IsDir() || fi.Mode().Perm() != 0o700 { |
| + t.Fatalf("cache directory = %v, %v; want a 0700 directory under $CARLOS_DATA_DIR", fi, err) |
| + } |
| +} |
| + |
| +// D12: the edge answers from the policy the edges file writer fills. The |
| +// agent creates it before the loop has a store, so the loop binds its |
| +// manifest cache; the edge sees the writer's first settled snapshot, and |
| +// nothing before it. |
| +func TestAssetCacheArmingSharesTheWritersPolicy(t *testing.T) { |
| + t.Setenv("CARLOS_DATA_DIR", t.TempDir()) |
| + t.Setenv("CARLOS_ASSET_CACHE", "1") |
| + w := newAssetWorld(t) |
| + w.ship("v1", "/assets/") |
| + w.instance("shop.example.com", assetGen1, "v1") |
| + w.confirm() |
| + |
| + p := armAssetPolicy(os.Getenv, w.reg, w.auth, nil, w.servingBuild) // as the agent builds it |
| + rec := &enableRecorder{} |
| + armEdgeAssetCache(os.Getenv, dataDir(), roomyFS, p, rec.enable) |
| + if rec.local == nil { |
| + t.Fatal("the edge was handed no policy") |
| + } |
| + if _, ok := rec.local.For("shop.example.com"); ok { |
| + t.Fatal("the edge's policy answered before the writer's first pass") |
| + } |
| + if r, ok := rec.local.(interface{ AssetsReady() bool }); !ok || r.AssetsReady() { |
| + t.Fatalf("AssetsReady before the first snapshot: implemented %v", ok) |
| + } |
| + |
| + p.bindManifests(w.cache) // what edgesFileLoop does with its store |
| + w.policy = p |
| + w.pass() |
| + a, ok := rec.local.For("shop.example.com") |
| + if !ok || a.Gen != assetGen1 || a.Account != "abc" || a.App != "shop" { |
| + t.Fatalf("after the writer's pass the edge's policy answers %+v %v", a, ok) |
| + } |
| + if !rec.local.Declared("shop.example.com", "v1", "/assets/app.js") { |
| + t.Fatal("the edge's policy does not see v1's declared paths") |
| + } |
| + if !rec.local.(interface{ AssetsReady() bool }).AssetsReady() { |
| + t.Fatal("AssetsReady is false after the first snapshot") |
| + } |
| +} |
| + |
| +// An Open or Statfs error leaves the cache off, with nothing handed to the |
| +// edge. |
| +func TestAssetCacheArmingFailureLeavesItOff(t *testing.T) { |
| + t.Setenv("CARLOS_ASSET_CACHE", "1") |
| + t.Run("statfs", func(t *testing.T) { |
| + t.Setenv("CARLOS_DATA_DIR", t.TempDir()) |
| + if _, rec := armFromEnv(t, newAssetWorld(t), spaceFS{err: assetcache.ErrUnsupported}); rec.calls != 0 { |
| + t.Fatalf("%d EnableAssetCache call(s) after a Statfs error", rec.calls) |
| + } |
| + }) |
| + t.Run("open", func(t *testing.T) { |
| + data := t.TempDir() |
| + t.Setenv("CARLOS_DATA_DIR", data) |
| + // A file where the cache directory goes: Open cannot create it. |
| + if err := os.WriteFile(filepath.Join(data, "asset-cache"), nil, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, rec := armFromEnv(t, newAssetWorld(t), roomyFS); rec.calls != 0 { |
| + t.Fatalf("%d EnableAssetCache call(s) after an Open error", rec.calls) |
| + } |
| + }) |
| +} |
| + |
| +func TestAssetCacheBudgetOverride(t *testing.T) { |
| + const total = 20 << 30 // a 20 GiB box gets 2 GiB (§7) |
| + for _, tc := range []struct { |
| + max string |
| + want int64 |
| + }{ |
| + {"", 2 << 30}, |
| + {"12345", 12345}, |
| + {"1073741824", 1 << 30}, |
| + {"0", 2 << 30}, |
| + {"-5", 2 << 30}, |
| + {"lots", 2 << 30}, |
| + {"1.5e9", 2 << 30}, |
| + } { |
| + t.Setenv("CARLOS_ASSET_CACHE_MAX", tc.max) |
| + if got := assetCacheBudget(os.Getenv, total); got != tc.want { |
| + t.Errorf("CARLOS_ASSET_CACHE_MAX=%q: budget %d, want %d", tc.max, got, tc.want) |
| + } |
| + } |
| + if got := assetCacheBudget(os.Getenv, 100<<30); got != assetcache.DefaultBudget(100<<30) { |
| + t.Errorf("a large box's default budget %d, want DefaultBudget's %d", got, assetcache.DefaultBudget(100<<30)) |
| + } |
| + |
| + // Through the store: on a filesystem too small for any default budget, |
| + // only the override arms the cache. |
| + t.Setenv("CARLOS_ASSET_CACHE", "1") |
| + tiny := spaceFS{total: 9, free: 9} |
| + t.Setenv("CARLOS_DATA_DIR", t.TempDir()) |
| + t.Setenv("CARLOS_ASSET_CACHE_MAX", "") |
| + if _, rec := armFromEnv(t, newAssetWorld(t), tiny); rec.calls != 0 { |
| + t.Fatal("a zero default budget armed the cache") |
| + } |
| + t.Setenv("CARLOS_DATA_DIR", t.TempDir()) |
| + t.Setenv("CARLOS_ASSET_CACHE_MAX", "1048576") |
| + if _, rec := armFromEnv(t, newAssetWorld(t), tiny); rec.calls != 1 || rec.store == nil { |
| + t.Fatalf("the override did not arm the cache (%d call(s))", rec.calls) |
| + } |
| +} |
diff --git a/internal/host/assetpolicy.go b/internal/host/assetpolicy.go| index a0484c3b9..1769cd18f 100644 |
| --- a/internal/host/assetpolicy.go |
| +++ b/internal/host/assetpolicy.go |
| @@ -142,6 +142,26 @@ func armAssetPolicy(getenv func(string) string, reg *registry.Registry, auth *as |
| return &assetPolicy{reg: reg, auth: auth, manifests: manifests, serving: sb, written: map[string]writtenAssets{}} |
| } |
| +// bindManifests gives a policy built without a manifest cache the one the |
| +// edges file loop reads through its own store handle. The agent builds the |
| +// one policy before that loop has opened the store, and hands it to both the |
| +// loop and the edge (drift D12); the loop binds it once, before its first |
| +// pass. Like written and knownAt, manifests is the writer's alone: For, |
| +// Declared and AssetsReady never touch it, so the edge may already be |
| +// calling them. A policy that already has a cache keeps it. |
| +func (p *assetPolicy) bindManifests(c *assetManifestCache) { |
| + if p != nil && p.manifests == nil { |
| + p.manifests = c |
| + } |
| +} |
| + |
| +// AssetsReady reports whether the writer has stored its first settled |
| +// snapshot. Until it has, For answers false for every host because nothing |
| +// has been decided yet, not because a host stopped catching, and the edge's |
| +// sweep keeps the entries it would otherwise judge (§7). Safe for concurrent |
| +// calls. |
| +func (p *assetPolicy) AssetsReady() bool { return p.current() != nil } |
| + |
| // assetInputs is the registry state one decision reads. |
| type assetInputs struct { |
| byHost map[string]registry.Route |
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go| index ba1c1a8ad..46922b7d3 100644 |
| --- a/internal/host/edgesfile.go |
| +++ b/internal/host/edgesfile.go |
| @@ -875,13 +875,16 @@ func edgesFileSecretsFP(getenv func(string) string) string { |
| // with a log line when there is no deployment bucket. Single-box deployments: |
| // the file is published and nothing reads it yet. |
| // |
| -// With CARLOS_ASSET_CACHE=1 the file carries each catching host's assets |
| -// block (edge asset cache design §4.1), and two more things make a pass due: |
| -// a change in any local route's serving build (sb, the activator's |
| -// ServingGen; a generation switch changes no registry row), and an assets |
| -// rewrite coming due (assetPolicy.rewriteDue: a published at would advance |
| -// by 20 minutes or more, or the authority clocks first became known). |
| -func edgesFileLoop(reg *registry.Registry, sb servingBuild) { |
| +// With CARLOS_ASSET_CACHE=1 the agent hands it the box's asset policy |
| +// (assets; nil on an unarmed box), and the file carries each catching host's |
| +// assets block (edge asset cache design §4.1). Two more things then make a |
| +// pass due: a change in any local route's serving build (the policy's |
| +// servingBuild, the activator's ServingGen; a generation switch changes no |
| +// registry row), and an assets rewrite coming due (assetPolicy.rewriteDue: a |
| +// published at would advance by 20 minutes or more, or the authority clocks |
| +// first became known). The policy is the edge's too: its settled snapshots, |
| +// stored by this loop's passes, are what the box's own catch answers from. |
| +func edgesFileLoop(reg *registry.Registry, assets *assetPolicy) { |
| ctx := context.Background() |
| if shouldSkipPublisherElection(os.Getenv) { |
| log.Printf("agent: edges file loop is a platform-box job — skipped on a fleet box") |
| @@ -943,9 +946,11 @@ func edgesFileLoop(reg *registry.Registry, sb servingBuild) { |
| }) |
| } |
| // The asset cache's publication (design §4.1): nil, and so nothing at |
| - // all, unless the box is armed. The manifests are read from this loop's |
| - // store handle, the deployment bucket. |
| - assets := armAssetPolicy(os.Getenv, reg, boxAssetAuthority, newAssetManifestCache(store), sb) |
| + // all, unless the box is armed. The agent built the policy and hands the |
| + // same one to the edge (drift D12); its manifests are read from this |
| + // loop's store handle, the deployment bucket, bound here before the |
| + // first pass. |
| + assets.bindManifests(newAssetManifestCache(store)) |
| if assets != nil { |
| log.Printf("agent: edges file publishes asset-cache blocks (CARLOS_ASSET_CACHE=1)") |
| } |