carlos / platform Public

edge: home-box page cache at the LRU point

servePage answers an eligible, readable request from the page index
after the plan throttle and before the LRU, the rate limit and the
activator, falling through when the entry cannot be opened. A storable
GET whose answering process runs the current inputs is recorded by
pageRecorder, which reserves at the final status when pageAdmit keeps
the response, tees the body, and publishes after the proxy returns
(MarkOptIn first) unless a Set-Cookie trailer, a short body, an
overflow, or a changed route, current inputs or process inputs say
otherwise. The same writer sets Carlos-Cache on every opted-in or
marked response of an instance route, armed or not. An opted-in
instance never uses the LRU (cacheable). EnablePageCache puts the
index's Sweep on the asset sweep tick.

The host's asset policy answers DeclaresPrefix from the manifest cache
alone, whatever AssetsOff says, and reads an unread build's manifest in
a bounded, deduplicated background loader. The manifest cache is now
published through an atomic pointer by bindManifests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev bf3bd2618ba6d36d30f8af9610a503d9ba63656b parent caa38c8
11 files changed, +2,192 −19
  • internal/edge/assetarm.go +7 −0
  • internal/edge/assettypes.go +11 −0
  • internal/edge/edge.go +23 −1
  • internal/edge/pagecache.go +349 −0
  • internal/edge/pagecache_sim_test.go +156 −0
  • internal/edge/pagecache_test.go +1,057 −0
  • internal/edge/pagerecord.go +164 −0
  • internal/host/assetmanifests.go +20 −4
  • internal/host/assetpolicy.go +178 −13
  • internal/host/assetpolicy_test.go +226 −0
  • internal/host/edgesfile.go +1 −1

Intent

Human

<task-notification> <task-id>a25dffddbef0516f2</task-id> <tool-use-id>toolu_01RCjCthnW4GMfqhrHDqRYFY</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/a25dffddbef0516f2.output</output-file> <status>completed</status> <summary>Agent "Implement Task 6: current and launch inputs" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE. Fix round 1 is committed as a new commit (no amend), and the fix report is appended. Commits: - `caa38c88 activator: unpinned live-link launches publish unknown inputs` (new) - `bfbd844e activator: current inputs and per-process launch inputs, published when current` Fix: I published unknown inputs for unpinned launches instead of pinning. Pinning would change more than how the link is resolved: - **Flat:** `$0` changes for script apps, which `TestALiveExecGateGatesTheFlatLiveLinkSpawn/no_gate` pins, and wakes through a link outside the version store would start failing. - **Nested:** root would get a different start call. Cost: the Service's ordinary wake of an exec row already resolves the link once and runs that file (`settleWakeIdentity` then `startGenExe`), so it keeps caching. Hosts lose page storing only when a process starts on the unpinned live link with no gate: a live link outside the version store, the `startGen` fallback, or direct `Start`/`StartGen` callers. I have not measured this on a real box. Tests: the new regression `TestLiveLinkRepointBeforeExecPublishesNoInputs` (flat unpinned, flat gated, nested unpinned) failed on the pre-fix code and passes now. The Task 6 tests pass, along with the activator `Purge|Gen|Swap|ExecGate|LiveExecGate|Rootfs|Nested|Recovery|StartGen|ExecBackendStart` run (88 s), `TestCacheProcessInputs`, vet, and the darwin/windows builds. Concerns: the version-naming check for Task 10, stateless follower escrow never matching (safe), and the darwin/windows test-vet failures, now listed as pre-existing in the validation section. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-page-cache-1/.superpowers/sdd/2026-11-08-edge-page-cache-plan-1-home/task-6-report.md</result> <usage><subagent_tokens>289650</subagent_tokens><tool_uses>18</tool_uses><duration_ms>392691</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>box55us4d</task-id> <tool-use-id>toolu_01578iYdGqG4rvDRJsFX2xFE</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/box55us4d.output</output-file> <status>completed</status> <summary>Background command "Run scoped Astra re-review of Task 6 fix" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/edge/assetarm.go b/internal/edge/assetarm.go
index e539c12ee..11188baea 100644
--- a/internal/edge/assetarm.go
+++ b/internal/edge/assetarm.go
@@ -55,6 +55,13 @@ func (e *Edge) assetSweepLoop(st *assetState, every time.Duration, done <-chan s
if n := e.sweepAssets(st.clock()); n > 0 {
log.Printf("edge: asset cache sweep dropped %d entries no longer current", n)
}
+ // The page index's records whose objects the store no longer
+ // has (EnablePageCache), on the same tick.
+ if x := e.pages.Load(); x != nil {
+ if n := x.Sweep(); n > 0 {
+ log.Printf("edge: page cache sweep dropped %d pages the store no longer holds", n)
+ }
+ }
}
}
}
diff --git a/internal/edge/assettypes.go b/internal/edge/assettypes.go
index c0076cd26..f0bc56e74 100644
--- a/internal/edge/assettypes.go
+++ b/internal/edge/assettypes.go
@@ -41,3 +41,14 @@ type LocalAssets interface {
For(host string) (HostAssets, bool)
Declared(host, build, path string) bool
}
+
+// assetDeclarations is an optional LocalAssets method for the page cache
+// (edge page cache plan 1 Task 7, P2-9 and R2-5): whether build, run by the
+// route host, declares an asset prefix of path, whatever the route's
+// AssetsOff says. known is false when the answer is not held yet; the page
+// cache then bypasses. It never reads storage on the caller's goroutine.
+// internal/host's policy implements it; a LocalAssets that does not leaves
+// every declaration unknown, and so no page eligible.
+type assetDeclarations interface {
+ DeclaresPrefix(host, build, path string) (declared, known bool)
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 3d731d1f0..d8a861a47 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -58,6 +58,7 @@ import (
"github.com/carlosframework/platform/internal/geo"
"github.com/carlosframework/platform/internal/geoip"
"github.com/carlosframework/platform/internal/lbhealth"
+ "github.com/carlosframework/platform/internal/pageindex"
"github.com/carlosframework/platform/internal/plans"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/ratelimit"
@@ -311,6 +312,10 @@ type Edge struct {
// 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]
+ // pages, when non-nil, is the home box's page index (pagecache.go),
+ // stored by EnablePageCache. Nil serves no page and stores none; the
+ // page diagnostics still run.
+ pages atomic.Pointer[pageindex.Index]
// 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).
@@ -2677,6 +2682,14 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !e.planThrottleAdmit(w, r, up) {
return
}
+ // The page cache (pagecache.go): a hit is answered here, after the plan
+ // throttle and before the LRU, the rate limit and the activator, so it
+ // never wakes an instance. page is the request's page state (nil when
+ // the route is not an instance); its writer goes on below.
+ page, pageHit := e.servePage(w, r, host, up)
+ if pageHit {
+ return
+ }
// A forward row is never cached here (fleet public routes spec §4.8): the
// hub cannot see the fleet edge's gate, so a gated page stored here would
// be served without the cookie, and an app's Carlos-Purge stops at its
@@ -2687,9 +2700,13 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// (edge-held streams spec §3.8, r2 P2-7): a hub or hop that stored a
// finished stream would replay it instead of connecting the browser to
// the edge that holds it.
+ //
+ // An instance opted into the page cache never uses the LRU, in either
+ // direction, whatever this request, the route's eligibility or its inputs
+ // (page cache design §5.3). This is the one place that rule is checked.
cacheable := e.cache != nil && (r.Method == http.MethodGet || r.Method == http.MethodHead) &&
up.route.Kind != "status" && up.route.Kind != "static" && up.route.ImportGate == "" &&
- !up.route.IsForward() && !markedRequest(r)
+ !up.route.IsForward() && !markedRequest(r) && !e.pagesOptedIn(up)
var key CacheKey
if cacheable {
key = CacheKey{Host: host, Method: r.Method, Path: r.URL.Path, RawQuery: r.URL.RawQuery}
@@ -2720,6 +2737,11 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer release()
w = &slotWriter{ResponseWriter: w, release: release}
}
+ // The page writer (pagerecord.go): Carlos-Cache for opted-in and marked
+ // responses, and the recorder of a storable miss, under every branch
+ // below. end publishes or abandons the recording once they return.
+ w = page.wrap(w)
+ defer page.end()
if up.hibernating {
// Wake (or join an in-progress wake) before proxying; the activator
diff --git a/internal/edge/pagecache.go b/internal/edge/pagecache.go
new file mode 100644
index 000000000..c730a5615
--- /dev/null
+++ b/internal/edge/pagecache.go
@@ -0,0 +1,349 @@
+package edge
+
+import (
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/assetcache"
+ "github.com/carlosframework/platform/internal/pageindex"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The home box's page cache at the LRU point (edge page cache design §5,
+// §6.2; plan 1 Task 7). ServeHTTP asks servePage after the plan throttle and
+// before the LRU: an eligible, readable request is answered from the page
+// index when it holds a page rendered from the route's current inputs. Every
+// other request goes on to the app as before, and a storable one has its
+// marked response recorded into the index (pagerecord.go).
+//
+// Three rules hold whatever else happens:
+// - a page is stored only from a GET with no Cookie and no Authorization,
+// and served only to a request whose every cookie the page ignores;
+// - a page is served only while the route's current inputs (build and
+// config) are the ones it was rendered from, and stored only when the
+// answering process was started from those inputs, at the start and at
+// the end of the response;
+// - an opted-in instance never uses the LRU (ServeHTTP's cacheable).
+
+// EnablePageCache arms the page cache over x, the page index over this box's
+// asset store, and puts x.Sweep on the asset sweep's tick (assetSweepLoop).
+// Pages are eligible only while the asset cache is armed too: its policy
+// answers which paths the serving build declares as assets. nil disarms:
+// no page is served or stored, and the diagnostics still run.
+func (e *Edge) EnablePageCache(x *pageindex.Index) {
+ e.pages.Store(x)
+}
+
+// pageScopeOf is the scope up's pages live in: the route's account (as the
+// asset cache names it), its app, and its primary hostname. An alias of the
+// route shares the scope; the key keeps the hostname asked for.
+func pageScopeOf(up upstream) pageindex.Scope {
+ return pageindex.Scope{Account: release.RouteAccount(up.route), App: up.route.App, Instance: up.route.Host}
+}
+
+// pagesOptedIn reports whether up's instance holds a durable opt-in mark on
+// this box: then the LRU is off for it (ServeHTTP), whatever the request,
+// the route's eligibility or its inputs.
+func (e *Edge) pagesOptedIn(up upstream) bool {
+ x := e.pages.Load()
+ return x != nil && up.route.Kind == "instance" && x.OptedIn(pageScopeOf(up))
+}
+
+// pageRouteEligible is the route half of the page rule for a request to host
+// for path served by up. It returns the route's current inputs, and false
+// whenever any of these fails:
+// - the box is armed (EnablePageCache);
+// - the route is a ready instance this box runs: not a forward row, not
+// HA, not a sidecar, not unit-backed, not served over a tunnel, with no
+// password gate, no import gate and the page switch on;
+// - no plan throttle is active for the account, as the installed hook
+// says, whether or not this request was let through (R3-9);
+// - neither host's own entry nor the route's primary has path rows, and
+// the request was not dispatched by path to another route (P1-6);
+// - the serving build's asset declarations are known and path is not
+// under one of them (P2-9): those paths are the asset cache's;
+// - the route's current inputs are known.
+func (e *Edge) pageRouteEligible(host, path string, up upstream) (inputs string, ok bool) {
+ if e.pages.Load() == nil {
+ return "", false
+ }
+ rt := up.route
+ if rt.Kind != "instance" || rt.IsForward() || rt.HA || rt.IsSidecar() || rt.Backing == registry.BackingUnit ||
+ rt.Status != "ready" || rt.Gate != "" || rt.ImportGate != "" || rt.PagesOff || up.viaTunnel {
+ return "", false
+ }
+ if f := e.planThrottle.Load(); f != nil {
+ if _, on := (*f)(rt); on {
+ return "", false
+ }
+ }
+ m := e.current()
+ own, ok := lookupIn(m, host)
+ if !ok || own.paths != nil || own.route.Host != rt.Host {
+ return "", false
+ }
+ if primary, ok := m[rt.Host]; !ok || primary.paths != nil {
+ return "", false
+ }
+ st := e.assets.Load()
+ if st == nil || st.store == nil {
+ return "", false
+ }
+ d, ok := st.local.(assetDeclarations)
+ if !ok {
+ return "", false
+ }
+ if declared, known := d.DeclaresPrefix(rt.Host, rt.Version, path); !known || declared {
+ return "", false
+ }
+ in, ok := e.cache.CurrentInputs(rt)
+ if !ok || in == "" {
+ return "", false
+ }
+ return in, true
+}
+
+// pageReadable is the request half of the rule for reading the page cache:
+// GET or HEAD, no Range, not an upgrade, not a door call (here or
+// backhauled), not a held-stream request, no Authorization, a canonical
+// path, and a Cookie header (if any) whose every pair has a name. It returns
+// the request's cookie names, which the page found must all ignore.
+func pageReadable(r *http.Request) (cookieNames []string, ok bool) {
+ if r.Method != http.MethodGet && r.Method != http.MethodHead {
+ return nil, false
+ }
+ if _, ranged := r.Header["Range"]; ranged {
+ return nil, false
+ }
+ if isUpgradeRequest(r) || markedRequest(r) {
+ return nil, false
+ }
+ if _, door := doorCallerFrom(r.Context()); door || hopDoorFrom(r.Context()) {
+ return nil, false
+ }
+ if _, auth := r.Header["Authorization"]; auth {
+ return nil, false
+ }
+ if !canonicalAssetPath(r.URL) {
+ return nil, false
+ }
+ return pageCookieNames(r.Header)
+}
+
+// pageCookieNames lists the names in h's Cookie lines. A pair with no "=" or
+// an empty name is not a cookie this edge can match against an ignore list,
+// so the request is not readable (false).
+func pageCookieNames(h http.Header) ([]string, bool) {
+ var names []string
+ for _, line := range h.Values("Cookie") {
+ for _, pair := range strings.Split(line, ";") {
+ pair = strings.TrimSpace(pair)
+ if pair == "" {
+ continue
+ }
+ name, _, ok := strings.Cut(pair, "=")
+ name = strings.TrimSpace(name)
+ if !ok || name == "" {
+ return nil, false
+ }
+ names = append(names, name)
+ }
+ }
+ return names, true
+}
+
+// pageStorable is the request half of the rule for storing a page: a
+// readable GET carrying no Cookie and no Authorization header at all. A HEAD
+// is answered from a stored GET and is never stored itself, and a request
+// with ignorable cookies may hit a page but never creates one.
+func pageStorable(r *http.Request) bool {
+ if r.Method != http.MethodGet {
+ return false
+ }
+ if _, c := r.Header["Cookie"]; c {
+ return false
+ }
+ if _, auth := r.Header["Authorization"]; auth {
+ return false
+ }
+ _, ok := pageReadable(r)
+ return ok
+}
+
+// pageAdmit is the header-time rule for keeping a response (design §5.2):
+// the app's well-formed marker, status 200, no Set-Cookie (a header, or a
+// trailer announced or already present), a positive lifetime (s-maxage,
+// else max-age, capped at a year; private, no-store and no-cache refuse),
+// no no-transform, Vary absent or only Accept-Encoding, no Content-Range,
+// and Content-Encoding absent or identity. Any Content-Type is kept. The
+// body-time rules (size, a late Set-Cookie trailer, a short body, the
+// inputs at the end) are the recorder's.
+func pageAdmit(status int, h http.Header, mark *pageMark) (lifetime time.Duration, ok bool) {
+ if mark == nil || !mark.Marked || status != http.StatusOK {
+ return 0, false
+ }
+ if len(h.Values("Set-Cookie")) > 0 || hasTrailerSetCookie(h) || announcesTrailer(h, "Set-Cookie") {
+ return 0, false
+ }
+ cc := joinHeader(h, "Cache-Control")
+ if hasCCDirective(cc, "no-transform") {
+ return 0, false
+ }
+ lifetime, ok = parseMaxAge(cc)
+ if !ok || lifetime <= 0 {
+ return 0, false
+ }
+ lifetime = min(lifetime, maxAssetLifetime)
+ if !assetVaryOK(h) || len(h.Values("Content-Range")) > 0 {
+ return 0, false
+ }
+ for _, v := range h.Values("Content-Encoding") {
+ for _, tok := range strings.Split(v, ",") {
+ if tok = strings.TrimSpace(tok); tok != "" && !strings.EqualFold(tok, "identity") {
+ return 0, false
+ }
+ }
+ }
+ return lifetime, true
+}
+
+// announcesTrailer reports whether h's Trailer header names name.
+func announcesTrailer(h http.Header, name string) bool {
+ for _, v := range h.Values("Trailer") {
+ for _, n := range strings.Split(v, ",") {
+ if strings.EqualFold(strings.TrimSpace(n), name) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// pageAfterLookup, when set, runs between a page hit's Lookup and its
+// delivery. Tests only: it lets one evict the entry in that window (P1-8).
+var pageAfterLookup func(*assetcache.Entry)
+
+// pageServe is one request's page cache state, from the LRU point to the end
+// of its proxied response. It exists for every request to an instance route,
+// armed or not, because the diagnostics do.
+type pageServe struct {
+ e *Edge
+ r *http.Request
+ host string
+ up upstream
+
+ x *pageindex.Index // nil on an unarmed box
+ scope pageindex.Scope
+ optedIn bool // the instance held its mark when the request arrived
+
+ // Set when the request is recorded (step 3): eligible, storable, and
+ // answered by a process started from inputs.
+ storing bool
+ inputs string
+ key pageindex.Key
+ ticket pageindex.Ticket
+
+ rec *pageRecorder // set by wrap
+}
+
+// servePage is the page cache at the LRU point. It answers a hit itself
+// (served true). Otherwise it returns the request's state, which ServeHTTP
+// wraps the response in (wrap) and settles once the proxy has returned
+// (end); nil for a route that is not an instance.
+//
+// A hit needs an eligible route and a readable request, and a page rendered
+// from the route's current inputs whose ignore list covers every cookie the
+// request carries. A hit whose body cannot be opened (the entry was evicted
+// since the lookup) goes on down the miss path (P1-8). A miss is recorded
+// when the request is storable and the process that will answer it was
+// started from the current inputs.
+func (e *Edge) servePage(w http.ResponseWriter, r *http.Request, host string, up upstream) (ps *pageServe, served bool) {
+ if up.route.Kind != "instance" {
+ return nil, false
+ }
+ ps = &pageServe{e: e, r: r, host: host, up: up}
+ x := e.pages.Load()
+ if x == nil {
+ return ps, false
+ }
+ ps.x, ps.scope = x, pageScopeOf(up)
+ ps.optedIn = x.OptedIn(ps.scope)
+ inputs, ok := e.pageRouteEligible(host, r.URL.Path, up)
+ if !ok {
+ return ps, false
+ }
+ key := pageindex.Key{Host: host, Path: r.URL.Path, RawQuery: r.URL.RawQuery}
+ if cookies, ok := pageReadable(r); ok {
+ if ent, miss := x.Lookup(ps.scope, key, inputs, cookies); miss == pageindex.MissNone {
+ if pageAfterLookup != nil {
+ pageAfterLookup(ent)
+ }
+ if serveAssetEntry(w, r, ent, e.pageClock(), "hit") == nil {
+ return ps, true
+ }
+ }
+ }
+ if pageStorable(r) {
+ if pin, ok := e.cache.ProcessInputs(up.route.Host); ok && pin == inputs {
+ ps.storing, ps.inputs, ps.key = true, inputs, key
+ ps.ticket = x.Begin(ps.scope, inputs)
+ }
+ }
+ return ps, false
+}
+
+// pageClock is the clock pages are aged and expired by: the asset store's.
+func (e *Edge) pageClock() time.Time {
+ if st := e.assets.Load(); st != nil {
+ return st.clock()
+ }
+ return time.Now()
+}
+
+// wrap returns w wrapped in the request's page recorder: the diagnostic
+// writer for every proxied response of an instance route, and the recorder
+// when the request is being recorded. A nil ps (not an instance) returns w.
+func (ps *pageServe) wrap(w http.ResponseWriter) http.ResponseWriter {
+ if ps == nil {
+ return w
+ }
+ ps.rec = &pageRecorder{ResponseWriter: w, ps: ps, cl: -1}
+ return ps.rec
+}
+
+// end settles a recording once ServeHTTP's proxy has returned: it publishes
+// the page or abandons it (pageRecorder.finish). Deferred, so a proxy that
+// panics (httputil.ReverseProxy's ErrAbortHandler for a body that broke off)
+// abandons the recording and the panic goes on unchanged.
+func (ps *pageServe) end() {
+ if ps == nil || ps.rec == nil || ps.rec.pend == nil {
+ return
+ }
+ if p := recover(); p != nil {
+ ps.rec.abort()
+ panic(p)
+ }
+ ps.rec.finish()
+}
+
+// stillCurrent reports whether the page recorded for ps may still be
+// published: host and path still resolve to the same instance, with the same
+// scope, the route is still eligible, and its current inputs and its
+// process's published inputs both still equal the inputs the recording
+// began with. It reads the route afresh, so a reload that changed the build
+// or the row while the response was written is seen.
+func (ps *pageServe) stillCurrent() bool {
+ e := ps.e
+ cur, ok := e.lookupUpstreamPath(ps.host, ps.r.URL.Path)
+ if !ok || cur.route.Host != ps.up.route.Host || pageScopeOf(cur) != ps.scope {
+ return false
+ }
+ in, ok := e.pageRouteEligible(ps.host, ps.r.URL.Path, cur)
+ if !ok || in != ps.inputs {
+ return false
+ }
+ pin, ok := e.cache.ProcessInputs(cur.route.Host)
+ return ok && pin == ps.inputs
+}
diff --git a/internal/edge/pagecache_sim_test.go b/internal/edge/pagecache_sim_test.go
new file mode 100644
index 000000000..9be8c4d8a
--- /dev/null
+++ b/internal/edge/pagecache_sim_test.go
@@ -0,0 +1,156 @@
+package edge
+
+import (
+ "fmt"
+ "io"
+ "math/rand"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strconv"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/pageindex"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// TestPageSimulationNoPersonalLeak drives random requests through one armed
+// box serving two instances, and checks I2 and I3 at the serving point (edge
+// page cache design §12; plan 1 Task 7). Task 9's simulation adds reloads,
+// switches and departures on top of this one.
+//
+// The app's every body names the request it answered (an id, its host and
+// path, and whether it carried a cookie or Authorization). Marked paths opt
+// the instance in; unmarked ones are LRU-cacheable today, and are stored
+// from personal requests before the mark (the adversarial fixtures). The
+// oracle asserts:
+// - every page-cache hit carries an anonymous body for the same host and
+// path, and was asked for by a request with no Authorization and only
+// ignorable cookies;
+// - while an instance is opted in, no response comes from the LRU;
+// - before opt-in the LRU is today's, and is not judged.
+//
+// CARLOS_PAGE_SIM_SEED replays a seed; the seed is printed on failure.
+func TestPageSimulationNoPersonalLeak(t *testing.T) {
+ seed := time.Now().UnixNano()
+ if v := os.Getenv("CARLOS_PAGE_SIM_SEED"); v != "" {
+ n, err := strconv.ParseInt(v, 10, 64)
+ if err != nil {
+ t.Fatal(err)
+ }
+ seed = n
+ }
+ steps := 600
+ if testing.Short() {
+ steps = 150
+ }
+ rng := rand.New(rand.NewSource(seed))
+ defer func() {
+ if t.Failed() {
+ t.Logf("seed %d (replay with CARLOS_PAGE_SIM_SEED=%d)", seed, seed)
+ }
+ }()
+
+ const two = "two.example.com"
+ app := func(w http.ResponseWriter, r *http.Request) {
+ _, cookie := r.Header["Cookie"]
+ _, auth := r.Header["Authorization"]
+ body := fmt.Sprintf("id=%s host=%s path=%s cookie=%v auth=%v", r.Header.Get("X-Sim-Id"), r.Host, r.URL.RequestURI(), cookie, auth)
+ h := w.Header()
+ h.Set("Content-Type", "text/html")
+ if strings.HasPrefix(r.URL.Path, "/m") {
+ h.Set("Cache-Control", "public, s-maxage=600")
+ h.Set(pageCacheHeader, `on; ignore-cookies="consent"`)
+ } else {
+ h.Set("Cache-Control", "public, s-maxage=600")
+ }
+ io.WriteString(w, body)
+ }
+ s := newPCScene(t, app)
+ if err := s.reg.Upsert(registry.Route{Host: two, Kind: "instance", Addr: s.b.srv.Listener.Addr().String(),
+ Status: "ready", Account: "def", App: "shop", Version: pcBuild}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ s.publishFor(registry.Route{Host: two, Version: pcBuild})
+ scopes := map[string]pageindex.Scope{
+ pcHost: s.scope(),
+ two: {Account: "def", App: "shop", Instance: two},
+ }
+ hosts := []string{pcHost, two}
+ paths := []string{"/m1", "/m2?x=1", "/u1", "/u2"}
+ kinds := []string{"anon", "consent", "session", "consent+session", "auth"}
+
+ var ids atomic.Int64
+ // The adversarial fixtures: before either instance opts in, today's LRU
+ // stores personal answers to its unmarked paths.
+ for _, host := range hosts {
+ for _, path := range paths[2:] {
+ req := httptest.NewRequest(http.MethodGet, "http://"+host+path, nil)
+ req.Header.Set("X-Sim-Id", "seed")
+ req.Header.Set("Cookie", "session=seeded")
+ s.e.ServeHTTP(httptest.NewRecorder(), req)
+ }
+ }
+ if s.lruLen() == 0 {
+ t.Fatal("no personal LRU entries were seeded")
+ }
+ var pageHits, lruBefore int
+ for step := 0; step < steps; step++ {
+ host := hosts[rng.Intn(len(hosts))]
+ if rng.Intn(40) == 0 {
+ s.idx.Clear(scopes[host], pageindex.Clear{})
+ continue
+ }
+ path := paths[rng.Intn(len(paths))]
+ kind := kinds[rng.Intn(len(kinds))]
+ id := strconv.FormatInt(ids.Add(1), 10)
+ req := httptest.NewRequest(http.MethodGet, "http://"+host+path, nil)
+ req.Header.Set("X-Sim-Id", id)
+ switch kind {
+ case "consent":
+ req.Header.Set("Cookie", "consent=yes")
+ case "session":
+ req.Header.Set("Cookie", "session=s-"+id)
+ case "consent+session":
+ req.Header.Set("Cookie", "consent=yes; session=s-"+id)
+ case "auth":
+ req.Header.Set("Authorization", "Bearer t-"+id)
+ }
+ optedIn := s.idx.OptedIn(scopes[host])
+ rec := httptest.NewRecorder()
+ s.e.ServeHTTP(rec, req)
+ if rec.Code != 200 {
+ t.Fatalf("step %d: %s %s (%s) = %d", step, host, path, kind, rec.Code)
+ }
+ body := rec.Body.String()
+ fromApp := strings.HasPrefix(body, "id="+id+" ")
+ switch {
+ case rec.Header().Get(assetCacheHeader) == "hit":
+ pageHits++
+ if kind != "anon" && kind != "consent" {
+ t.Fatalf("step %d: a %s request to %s%s was answered from the page cache: %q", step, kind, host, path, body)
+ }
+ if !strings.HasSuffix(body, "cookie=false auth=false") {
+ t.Fatalf("step %d: a page hit for %s%s served a personal body: %q", step, host, path, body)
+ }
+ if !strings.Contains(body, " host="+host+" path="+path+" ") {
+ t.Fatalf("step %d: a page hit for %s%s served another page: %q", step, host, path, body)
+ }
+ case !fromApp:
+ if optedIn {
+ t.Fatalf("step %d: the LRU answered %s%s for an opted-in instance: %q", step, host, path, body)
+ }
+ lruBefore++
+ }
+ }
+ if pageHits == 0 {
+ t.Fatalf("the run produced no page hits (seed %d): the oracle judged nothing", seed)
+ }
+ t.Logf("seed %d: %d steps, %d page hits, %d LRU answers before opt-in", seed, steps, pageHits, lruBefore)
+}
diff --git a/internal/edge/pagecache_test.go b/internal/edge/pagecache_test.go
new file mode 100644
index 000000000..74e5d5eb1
--- /dev/null
+++ b/internal/edge/pagecache_test.go
@@ -0,0 +1,1057 @@
+package edge
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/assetcache"
+ "github.com/carlosframework/platform/internal/pageindex"
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The home box's page cache at the LRU point (edge page cache plan 1, Task
+// 7). One Edge over a real registry, a real asset store and a real page
+// index on temporary directories, a fake asset policy that also answers the
+// page cache's DeclaresPrefix, and a fake config file the scene's current
+// inputs are read from, as the activator reads the web env layers.
+
+const (
+ pcHost = "blog.example.com"
+ pcBuild = "v1"
+ pcBody = "<!doctype html><p>hello</p>"
+)
+
+// pcDecl is the asset policy as the page cache sees it: LocalAssets (For
+// answers nothing unless set: the instance catches no assets) and
+// DeclaresPrefix, which answers from the builds loaded into it and queues
+// the rest. load is the background read, the one place this fake reads
+// "storage"; reads counts it.
+type pcDecl struct {
+ fakeLocalAssets
+ dmu sync.Mutex
+ decls map[string][]string // build -> declared prefixes; absent: not read
+ wants []string
+ reads atomic.Int64
+}
+
+func newPCDecl() *pcDecl {
+ return &pcDecl{fakeLocalAssets: fakeLocalAssets{hosts: map[string]HostAssets{}, builds: map[string]bool{}}, decls: map[string][]string{}}
+}
+
+func (d *pcDecl) DeclaresPrefix(host, build, path string) (declared, known bool) {
+ d.dmu.Lock()
+ defer d.dmu.Unlock()
+ p, ok := d.decls[build]
+ if !ok {
+ d.wants = append(d.wants, host+" "+build)
+ return false, false
+ }
+ return assetPrefixMatch(p, path), true
+}
+
+func (d *pcDecl) load(build string, prefixes ...string) {
+ d.reads.Add(1)
+ d.dmu.Lock()
+ defer d.dmu.Unlock()
+ d.decls[build] = prefixes
+}
+
+func (d *pcDecl) forget(build string) {
+ d.dmu.Lock()
+ defer d.dmu.Unlock()
+ delete(d.decls, build)
+}
+
+func (d *pcDecl) wanted() []string {
+ d.dmu.Lock()
+ defer d.dmu.Unlock()
+ return slices.Clone(d.wants)
+}
+
+// pcActivator is the activator as a page test needs it: every request to a
+// hibernating route counts as a wake ask, and a wake publishes the inputs the
+// new process was started from (onWake), as a spawn does.
+type pcActivator struct {
+ served atomic.Int64
+ onWake func(rt registry.Route)
+}
+
+func (a *pcActivator) ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) bool {
+ a.served.Add(1)
+ if a.onWake != nil {
+ a.onWake(rt)
+ }
+ proxy.ServeHTTP(w, r)
+ return true
+}
+
+func (a *pcActivator) RetireExcept(map[string]bool) {}
+func (a *pcActivator) AdmitHeldLeg(context.Context, registry.Route) (HeldLeg, error) {
+ return nil, errors.New("asleep")
+}
+func (a *pcActivator) HeldAdmissible(string) bool { return false }
+func (a *pcActivator) SetHeldWakeHook(func(string)) {}
+
+type pcScene struct {
+ t *testing.T
+ e *Edge
+ reg *registry.Registry
+ b *laBackend
+ store *assetcache.Store
+ idx *pageindex.Index
+ decl *pcDecl
+ act *pcActivator
+ cfg string // the fake web env file the current inputs are read from
+
+ mu sync.Mutex
+ rt registry.Route
+
+ inputsUnknown atomic.Bool
+}
+
+// newPCScene is one armed box serving pcHost (account abc, app blog, build
+// v1) from one backend, with the process's inputs published as a spawn would
+// publish them.
+func newPCScene(t *testing.T, h http.HandlerFunc, mods ...func(*registry.Route)) *pcScene {
+ t.Helper()
+ s := &pcScene{t: t, b: newLABackend(t, h), reg: openReg(t), act: &pcActivator{}, decl: newPCDecl()}
+ s.rt = registry.Route{Host: pcHost, Kind: "instance", Addr: s.b.srv.Listener.Addr().String(),
+ Status: "ready", Account: "abc", App: "blog", Version: pcBuild}
+ for _, m := range mods {
+ m(&s.rt)
+ }
+ if err := s.reg.Upsert(s.rt); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ s.cfg = filepath.Join(t.TempDir(), "web.env")
+ if err := os.WriteFile(s.cfg, []byte("GREETING=hello\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ e, err := New(s.reg, s.act)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ t.Cleanup(e.probers.Stop)
+ s.e = e
+ c := NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes)
+ e.EnableCache(c)
+ c.SetCurrentInputs(s.currentInputs)
+ s.act.onWake = func(rt registry.Route) { s.publishFor(rt) }
+ s.publish()
+ s.decl.decls[pcBuild] = []string{"/assets/"}
+ s.decl.decls["v2"] = []string{"/assets/"}
+ s.store = openLAStore(t)
+ e.assets.Store(&assetState{store: s.store, local: s.decl, now: time.Now})
+ idx, err := pageindex.Open(pageindex.Config{Store: s.store, MarkDir: filepath.Join(t.TempDir(), "marks")})
+ if err != nil {
+ t.Fatalf("open page index: %v", err)
+ }
+ s.idx = idx
+ e.EnablePageCache(idx)
+ return s
+}
+
+// currentInputs is the scene's CurrentInputs: the route's build and the
+// config file's bytes (or their absence), unknown when the test says so.
+func (s *pcScene) currentInputs(rt registry.Route) (string, bool) {
+ if s.inputsUnknown.Load() || rt.Version == "" {
+ return "", false
+ }
+ cfg := "<no config>"
+ if b, err := os.ReadFile(s.cfg); err == nil {
+ cfg = string(b)
+ }
+ return rt.Version + "\x00" + cfg, true
+}
+
+// publish publishes the current route's inputs as its process's, as a spawn
+// that became current does.
+func (s *pcScene) publish() {
+ s.mu.Lock()
+ rt := s.rt
+ s.mu.Unlock()
+ s.publishFor(rt)
+}
+
+func (s *pcScene) publishFor(rt registry.Route) {
+ in, _ := s.currentInputs(rt)
+ s.e.cache.NoteProcessInputs(rt.Host, in)
+}
+
+// setRoute changes the route row and reloads, with no spawn.
+func (s *pcScene) setRoute(mod func(*registry.Route)) {
+ s.t.Helper()
+ s.mu.Lock()
+ mod(&s.rt)
+ rt := s.rt
+ s.mu.Unlock()
+ if err := s.reg.Upsert(rt); err != nil {
+ s.t.Fatalf("upsert: %v", err)
+ }
+ if err := s.e.Reload(); err != nil {
+ s.t.Fatalf("reload: %v", err)
+ }
+}
+
+func (s *pcScene) writeConfig(body string) {
+ s.t.Helper()
+ if err := os.WriteFile(s.cfg, []byte(body), 0o600); err != nil {
+ s.t.Fatal(err)
+ }
+}
+
+func (s *pcScene) do(method, target string, hdr ...string) *httptest.ResponseRecorder {
+ s.t.Helper()
+ req := httptest.NewRequest(method, target, nil)
+ for i := 0; i+1 < len(hdr); i += 2 {
+ req.Header.Add(hdr[i], hdr[i+1])
+ }
+ rec := httptest.NewRecorder()
+ s.e.ServeHTTP(rec, req)
+ wantNoPageMark(s.t, method+" "+target, rec.Header())
+ return rec
+}
+
+func (s *pcScene) get(path string, hdr ...string) *httptest.ResponseRecorder {
+ s.t.Helper()
+ return s.do(http.MethodGet, "http://"+pcHost+path, hdr...)
+}
+
+func (s *pcScene) scope() pageindex.Scope {
+ return pageindex.Scope{Account: "abc", App: "blog", Instance: pcHost}
+}
+
+// pages counts the page objects in the store.
+func (s *pcScene) pages() int {
+ n := 0
+ s.store.Retain(func(k assetcache.Key) bool {
+ if assetcache.IsPageKey(k) {
+ n++
+ }
+ return true
+ })
+ return n
+}
+
+func (s *pcScene) lruLen() int {
+ s.e.cache.mu.Lock()
+ defer s.e.cache.mu.Unlock()
+ return len(s.e.cache.entries)
+}
+
+// wantNothingStored fails when any page is stored or reserved, or the LRU
+// holds anything.
+func (s *pcScene) wantNothingStored(why string) {
+ s.t.Helper()
+ if n := s.pages(); n != 0 {
+ s.t.Fatalf("%s: %d pages stored, want none", why, n)
+ }
+ if st := s.store.Stats(); st.Reserved != 0 {
+ s.t.Fatalf("%s: %d bytes still reserved", why, st.Reserved)
+ }
+ if n := s.lruLen(); n != 0 {
+ s.t.Fatalf("%s: the LRU holds %d entries, want none", why, n)
+ }
+}
+
+func wantBody(t *testing.T, rec *httptest.ResponseRecorder, code int, body string) {
+ t.Helper()
+ if rec.Code != code || rec.Body.String() != body {
+ t.Fatalf("answer = %d %q, want %d %q", rec.Code, rec.Body.String(), code, body)
+ }
+}
+
+// pageOK answers body as a marked page (s-maxage 600), with extra headers
+// (an empty value deletes the header).
+func pageOK(body string, extra ...string) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ h := w.Header()
+ h.Set("Content-Type", "text/html; charset=utf-8")
+ h.Set("Cache-Control", "public, s-maxage=600")
+ h.Set(pageCacheHeader, "on")
+ for i := 0; i+1 < len(extra); i += 2 {
+ if extra[i+1] == "" {
+ h.Del(extra[i])
+ } else {
+ h.Set(extra[i], extra[i+1])
+ }
+ }
+ h.Set("Content-Length", strconv.Itoa(len(body)))
+ io.WriteString(w, body)
+ }
+}
+
+// ---- the core path ---------------------------------------------------------
+
+func TestPageMissThenHitWithoutApp(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody))
+ first := s.get("/p")
+ wantCache(t, first, "miss")
+ wantBody(t, first, 200, pcBody)
+ second := s.get("/p")
+ wantCache(t, second, "hit")
+ wantBody(t, second, 200, pcBody)
+ if second.Header().Get("X-Carlos-Version") != "" {
+ t.Fatal("a hit carries X-Carlos-Version")
+ }
+ if n := s.b.n.Load(); n != 1 {
+ t.Fatalf("the app saw %d requests, want 1", n)
+ }
+ // The raw query is part of the key.
+ wantCache(t, s.get("/p?x=1"), "miss")
+ wantCache(t, s.get("/p?x=1"), "hit")
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("the app saw %d requests, want 2", n)
+ }
+ if !s.idx.OptedIn(s.scope()) {
+ t.Fatal("publishing a page did not opt the instance in")
+ }
+ if n := s.lruLen(); n != 0 {
+ t.Fatalf("the LRU holds %d entries for marked pages", n)
+ }
+}
+
+func TestPageHitOnHibernatingRouteDoesNotWake(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody), func(r *registry.Route) { r.Hibernate = true })
+ wantCache(t, s.get("/p"), "miss")
+ if n := s.act.served.Load(); n != 1 {
+ t.Fatalf("the miss reached the activator %d times, want 1", n)
+ }
+ hit := s.get("/p")
+ wantCache(t, hit, "hit")
+ wantBody(t, hit, 200, pcBody)
+ if n := s.act.served.Load(); n != 1 {
+ t.Fatalf("a hit reached the activator (%d asks)", n)
+ }
+}
+
+// ---- responses that must not be stored -------------------------------------
+
+// wantPageRefused asks for path twice: both reach the app, the visitor gets the
+// app's answer, and nothing is stored in either cache.
+func wantPageRefused(t *testing.T, s *pcScene, path string, code int, body string, header string) {
+ t.Helper()
+ before := s.b.n.Load()
+ for i := 0; i < 2; i++ {
+ rec := s.get(path)
+ wantBody(t, rec, code, body)
+ if header != "" {
+ wantCache(t, rec, header)
+ }
+ }
+ if n := s.b.n.Load() - before; n != 2 {
+ t.Fatalf("the app saw %d of 2 requests", n)
+ }
+ s.wantNothingStored("a refused response")
+ if s.idx.OptedIn(s.scope()) {
+ t.Fatal("a refused response opted the instance in")
+ }
+}
+
+func TestPageRefusesSetCookie(t *testing.T) {
+ t.Run("header", func(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody, "Set-Cookie", "session=1"))
+ wantPageRefused(t, s, "/p", 200, pcBody, "bypass")
+ })
+ t.Run("announced trailer", func(t *testing.T) {
+ s := newPCScene(t, func(w http.ResponseWriter, r *http.Request) {
+ h := w.Header()
+ h.Set("Content-Type", "text/html")
+ h.Set("Cache-Control", "public, s-maxage=600")
+ h.Set(pageCacheHeader, "on")
+ h.Set("Trailer", "Set-Cookie")
+ io.WriteString(w, pcBody)
+ h.Set("Set-Cookie", "session=1")
+ })
+ wantPageRefused(t, s, "/p", 200, pcBody, "")
+ })
+ t.Run("unannounced trailer", func(t *testing.T) {
+ s := newPCScene(t, func(w http.ResponseWriter, r *http.Request) {
+ h := w.Header()
+ h.Set("Content-Type", "text/html")
+ h.Set("Cache-Control", "public, s-maxage=600")
+ h.Set(pageCacheHeader, "on")
+ io.WriteString(w, pcBody)
+ w.(http.Flusher).Flush()
+ h.Set(http.TrailerPrefix+"Set-Cookie", "session=1")
+ })
+ wantPageRefused(t, s, "/p", 200, pcBody, "")
+ })
+}
+
+func TestPageRefusesVaryCookie(t *testing.T) {
+ for _, vary := range []string{"Cookie", "Accept-Encoding, Cookie", "*", "Accept-Language"} {
+ t.Run(vary, func(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody, "Vary", vary))
+ wantPageRefused(t, s, "/p", 200, pcBody, "bypass")
+ })
+ }
+ t.Run("Accept-Encoding is kept", func(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody, "Vary", "Accept-Encoding"))
+ wantCache(t, s.get("/p"), "miss")
+ wantCache(t, s.get("/p"), "hit")
+ })
+}
+
+func TestPageRefusesNon200(t *testing.T) {
+ for _, code := range []int{201, 203, 301, 404, 500} {
+ t.Run(strconv.Itoa(code), func(t *testing.T) {
+ s := newPCScene(t, func(w http.ResponseWriter, r *http.Request) {
+ h := w.Header()
+ h.Set("Content-Type", "text/html")
+ h.Set("Cache-Control", "public, s-maxage=600")
+ h.Set(pageCacheHeader, "on")
+ if code == 301 {
+ h.Set("Location", "/elsewhere")
+ }
+ w.WriteHeader(code)
+ io.WriteString(w, "status")
+ })
+ wantPageRefused(t, s, "/p", code, "status", "bypass")
+ })
+ }
+}
+
+func TestPageRefusesPrivate(t *testing.T) {
+ for _, cc := range []string{"private, s-maxage=600", "public, no-store, max-age=600", "no-cache, s-maxage=600",
+ "public", "max-age=0", "s-maxage=0, max-age=600", "s-maxage=x", "public, no-transform, s-maxage=600"} {
+ t.Run(cc, func(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody, "Cache-Control", cc))
+ wantPageRefused(t, s, "/p", 200, pcBody, "bypass")
+ })
+ }
+ t.Run("content-range", func(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody, "Content-Range", "bytes 0-26/27"))
+ wantPageRefused(t, s, "/p", 200, pcBody, "bypass")
+ })
+ t.Run("lifetime capped at a year", func(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody, "Cache-Control", "public, max-age=999999999"))
+ wantCache(t, s.get("/p"), "miss")
+ ent, miss := s.idx.Lookup(s.scope(), pageindex.Key{Host: pcHost, Path: "/p"}, s.inputs(), nil)
+ if miss != pageindex.MissNone {
+ t.Fatalf("lookup = %v", miss)
+ }
+ if ent.Meta.Lifetime != maxAssetLifetime {
+ t.Fatalf("lifetime = %v, want %v", ent.Meta.Lifetime, maxAssetLifetime)
+ }
+ })
+}
+
+func (s *pcScene) inputs() string {
+ s.mu.Lock()
+ rt := s.rt
+ s.mu.Unlock()
+ in, _ := s.currentInputs(rt)
+ return in
+}
+
+// Review Focus 2: an app that compresses its own page is passed through
+// byte for byte, never compressed twice, and not stored.
+func TestPageRefusesAppGzip(t *testing.T) {
+ var zipped bytes.Buffer
+ zw := gzip.NewWriter(&zipped)
+ io.WriteString(zw, strings.Repeat(pcBody, 100))
+ zw.Close()
+ raw := zipped.String()
+ s := newPCScene(t, pageOK(raw, "Content-Encoding", "gzip", "Vary", "Accept-Encoding"))
+ for i := 0; i < 2; i++ {
+ rec := s.get("/p", "Accept-Encoding", "gzip")
+ wantCache(t, rec, "bypass")
+ if got := rec.Header().Values("Content-Encoding"); len(got) != 1 || got[0] != "gzip" {
+ t.Fatalf("Content-Encoding = %q, want one gzip", got)
+ }
+ if rec.Body.String() != raw {
+ t.Fatalf("the app's gzip body was changed on the way (%d bytes, want %d)", rec.Body.Len(), len(raw))
+ }
+ }
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("the app saw %d requests, want 2", n)
+ }
+ s.wantNothingStored("an app-compressed page")
+}
+
+// Review Focus 3: a marked response with no Content-Length that grows past
+// MaxBody reaches the visitor whole, and nothing is stored or left
+// reserved.
+func TestPageOverflowStreamsAndStoresNothing(t *testing.T) {
+ chunk := strings.Repeat("x", 64<<10)
+ total := pageindex.MaxBody + len(chunk)
+ s := newPCScene(t, func(w http.ResponseWriter, r *http.Request) {
+ h := w.Header()
+ h.Set("Content-Type", "text/plain")
+ h.Set("Cache-Control", "public, s-maxage=600")
+ h.Set(pageCacheHeader, "on")
+ for n := 0; n < total; n += len(chunk) {
+ io.WriteString(w, chunk)
+ if n == 0 {
+ w.(http.Flusher).Flush()
+ }
+ }
+ })
+ for i := 0; i < 2; i++ {
+ rec := s.get("/big")
+ if rec.Code != 200 || rec.Body.Len() != total {
+ t.Fatalf("request %d = %d with %d bytes, want 200 with %d", i, rec.Code, rec.Body.Len(), total)
+ }
+ }
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("the app saw %d requests, want 2", n)
+ }
+ s.wantNothingStored("an overflowing page")
+ if st := s.store.Stats(); st.Entries != 0 {
+ t.Fatalf("the store holds %d entries", st.Entries)
+ }
+}
+
+// ---- requests that bypass --------------------------------------------------
+
+// Review Focus 4: a marked response to a request carrying a cookie is
+// stored in neither cache, and a later anonymous request still misses.
+func TestPageCookieRequestNotStoredAnywhere(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody))
+ rec := s.get("/p", "Cookie", "session=secret")
+ wantCache(t, rec, "bypass")
+ wantBody(t, rec, 200, pcBody)
+ s.wantNothingStored("a cookie request")
+ if s.idx.OptedIn(s.scope()) {
+ t.Fatal("a cookie request opted the instance in")
+ }
+ wantCache(t, s.get("/p"), "miss")
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("the app saw %d requests, want 2: the anonymous one was answered from a cache", n)
+ }
+ wantCache(t, s.get("/p"), "hit")
+}
+
+func TestPageIgnoredCookieHits(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody, pageCacheHeader, `on; ignore-cookies="consent, theme"`))
+ wantCache(t, s.get("/p"), "miss")
+ for _, c := range []string{"consent=yes", "consent=yes; theme=dark", "theme=dark"} {
+ rec := s.get("/p", "Cookie", c)
+ wantCache(t, rec, "hit")
+ wantBody(t, rec, 200, pcBody)
+ }
+ if n := s.b.n.Load(); n != 1 {
+ t.Fatalf("the app saw %d requests, want 1", n)
+ }
+ for _, c := range []string{"session=1", "consent=yes; session=1", "consent", "=x"} {
+ rec := s.get("/p", "Cookie", c)
+ wantCache(t, rec, "bypass")
+ }
+ if n := s.b.n.Load(); n != 5 {
+ t.Fatalf("the app saw %d requests, want 5", n)
+ }
+ // An ignorable cookie can hit an entry but never creates one.
+ wantCache(t, s.get("/q", "Cookie", "consent=yes"), "bypass")
+ wantCache(t, s.get("/q"), "miss")
+}
+
+func TestPageAuthorizationBypasses(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody))
+ wantCache(t, s.get("/p"), "miss")
+ rec := s.get("/p", "Authorization", "Bearer secret")
+ wantCache(t, rec, "bypass")
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("an authorized request was answered from the page cache (app saw %d)", n)
+ }
+ wantCache(t, s.get("/q", "Authorization", "Bearer secret"), "bypass")
+ if n := s.pages(); n != 1 {
+ t.Fatalf("%d pages stored, want only the anonymous one", n)
+ }
+}
+
+// ---- hit behaviour ---------------------------------------------------------
+
+// Review Focus 1: a Range request bypasses, a HEAD hit gets headers and no
+// body, a matching If-None-Match gets 304, and a HEAD miss is not stored.
+func TestPageHeadRangeConditional(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody, "ETag", `"p-1"`))
+ wantCache(t, s.get("/p"), "miss")
+
+ head := s.do(http.MethodHead, "http://"+pcHost+"/p")
+ wantCache(t, head, "hit")
+ if head.Code != 200 || head.Body.Len() != 0 {
+ t.Fatalf("HEAD hit = %d with %d body bytes", head.Code, head.Body.Len())
+ }
+ if cl := head.Header().Get("Content-Length"); cl != strconv.Itoa(len(pcBody)) {
+ t.Fatalf("HEAD Content-Length = %q", cl)
+ }
+
+ cond := s.get("/p", "If-None-Match", `"p-1"`)
+ wantCache(t, cond, "hit")
+ if cond.Code != http.StatusNotModified || cond.Body.Len() != 0 {
+ t.Fatalf("conditional hit = %d with %d bytes, want 304", cond.Code, cond.Body.Len())
+ }
+ if n := s.b.n.Load(); n != 1 {
+ t.Fatalf("the app saw %d requests, want 1", n)
+ }
+
+ rng := s.get("/p", "Range", "bytes=0-3")
+ wantCache(t, rng, "bypass")
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("a Range request was answered from the page cache (app saw %d)", n)
+ }
+
+ headMiss := s.do(http.MethodHead, "http://"+pcHost+"/h")
+ wantCache(t, headMiss, "bypass")
+ if n := s.pages(); n != 1 {
+ t.Fatalf("a HEAD miss was stored (%d pages)", n)
+ }
+ wantCache(t, s.get("/h"), "miss")
+}
+
+// ---- inputs (R2-1, R2-2) ---------------------------------------------------
+
+// sleepingChangeMisses caches /p, sleeps the route, applies change with no
+// spawn, and then asks only for /p: it misses, and the activator is asked to
+// wake. The process the wake starts publishes the new inputs, and the page
+// is cached afresh from it.
+func sleepingChangeMisses(t *testing.T, change func(s *pcScene)) {
+ s := newPCScene(t, pageOK(pcBody))
+ wantCache(t, s.get("/p"), "miss")
+ wantCache(t, s.get("/p"), "hit")
+ s.setRoute(func(r *registry.Route) { r.Hibernate = true })
+ wantCache(t, s.get("/p"), "hit") // asleep and unchanged: still a hit, no wake
+ if n := s.act.served.Load(); n != 0 {
+ t.Fatalf("a hit reached the activator (%d asks)", n)
+ }
+ change(s)
+ rec := s.get("/p")
+ if rec.Header().Get(assetCacheHeader) == "hit" {
+ t.Fatal("a page rendered from the old inputs was served after they changed")
+ }
+ wantBody(t, rec, 200, pcBody)
+ if n := s.act.served.Load(); n != 1 {
+ t.Fatalf("the activator was asked %d times, want 1 (a wake)", n)
+ }
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("the app saw %d requests, want 2", n)
+ }
+ wantCache(t, s.get("/p"), "miss")
+ wantCache(t, s.get("/p"), "hit")
+}
+
+func TestPageSleepingNewBuildMisses(t *testing.T) {
+ sleepingChangeMisses(t, func(s *pcScene) {
+ s.setRoute(func(r *registry.Route) { r.Version = "v2" })
+ })
+}
+
+func TestPageSleepingConfigChangeMisses(t *testing.T) {
+ t.Run("edited", func(t *testing.T) {
+ sleepingChangeMisses(t, func(s *pcScene) { s.writeConfig("GREETING=bonjour\n") })
+ })
+ t.Run("removed", func(t *testing.T) {
+ sleepingChangeMisses(t, func(s *pcScene) {
+ if err := os.Remove(s.cfg); err != nil {
+ t.Fatal(err)
+ }
+ })
+ })
+}
+
+func TestPageSameInputsWakeKeepsHits(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody), func(r *registry.Route) { r.Hibernate = true })
+ wantCache(t, s.get("/p"), "miss")
+ wantCache(t, s.get("/p"), "hit")
+ // Another URL wakes the instance; nothing changed, so the new process
+ // publishes the same inputs.
+ wantCache(t, s.get("/other"), "miss")
+ if n := s.act.served.Load(); n != 2 {
+ t.Fatalf("the activator was asked %d times, want 2", n)
+ }
+ rec := s.get("/p")
+ wantCache(t, rec, "hit")
+ wantBody(t, rec, 200, pcBody)
+ if n := s.act.served.Load(); n != 2 {
+ t.Fatalf("a hit after a same-inputs wake reached the activator")
+ }
+}
+
+// The current inputs change while the answering process still runs the old
+// ones (a staging window): its marked response is bypass and is not stored.
+// The same holds when either changes while the response is being written.
+func TestPageOldProcessDuringStagingNotStored(t *testing.T) {
+ t.Run("before the request", func(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody))
+ s.writeConfig("GREETING=bonjour\n")
+ rec := s.get("/p")
+ wantCache(t, rec, "bypass")
+ wantBody(t, rec, 200, pcBody)
+ s.wantNothingStored("an old process's answer")
+ s.publish() // the new process becomes current
+ wantCache(t, s.get("/p"), "miss")
+ wantCache(t, s.get("/p"), "hit")
+ })
+ t.Run("current inputs change mid-response", func(t *testing.T) {
+ var s *pcScene
+ var once sync.Once
+ s = newPCScene(t, func(w http.ResponseWriter, r *http.Request) {
+ once.Do(func() { s.writeConfig("GREETING=bonjour\n") })
+ pageOK(pcBody)(w, r)
+ })
+ wantBody(t, s.get("/p"), 200, pcBody)
+ s.wantNothingStored("an answer whose inputs changed under it")
+ })
+ t.Run("process replaced mid-response", func(t *testing.T) {
+ var s *pcScene
+ var once sync.Once
+ s = newPCScene(t, func(w http.ResponseWriter, r *http.Request) {
+ once.Do(func() { s.e.cache.NoteProcessInputs(pcHost, "someone else") })
+ pageOK(pcBody)(w, r)
+ })
+ wantBody(t, s.get("/p"), 200, pcBody)
+ s.wantNothingStored("an answer whose process was replaced under it")
+ })
+ t.Run("route reloaded mid-response", func(t *testing.T) {
+ var s *pcScene
+ var once sync.Once
+ s = newPCScene(t, func(w http.ResponseWriter, r *http.Request) {
+ once.Do(func() { s.setRoute(func(r *registry.Route) { r.Version = "v2" }) })
+ pageOK(pcBody)(w, r)
+ })
+ wantBody(t, s.get("/p"), 200, pcBody)
+ s.wantNothingStored("an answer whose route changed build under it")
+ })
+}
+
+// R2-3: a unit-backed instance is refused.
+func TestPageUnitBackedBypasses(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody), func(r *registry.Route) { r.Backing = registry.BackingUnit })
+ wantPageRefused(t, s, "/p", 200, pcBody, "bypass")
+}
+
+// ---- failed delivery (P1-8) ------------------------------------------------
+
+func TestPageEvictedBetweenLookupAndOpenFallsThrough(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody))
+ wantCache(t, s.get("/p"), "miss")
+ var evicted atomic.Int64
+ pageAfterLookup = func(ent *assetcache.Entry) {
+ if s.store.Delete(ent.Meta.Key) {
+ evicted.Add(1)
+ }
+ }
+ t.Cleanup(func() { pageAfterLookup = nil })
+ rec := s.get("/p")
+ if evicted.Load() != 1 {
+ t.Fatal("the seam evicted nothing")
+ }
+ wantBody(t, rec, 200, pcBody)
+ if rec.Header().Get(assetCacheHeader) == "hit" {
+ t.Fatal("an evicted page was answered hit")
+ }
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("the app saw %d requests, want 2", n)
+ }
+ pageAfterLookup = nil
+ wantCache(t, s.get("/p"), "hit")
+}
+
+// ---- opt-in and the LRU ----------------------------------------------------
+
+// Once an instance is opted in, the LRU is off for it: what it stored before
+// the mark is not served, and nothing new is stored, marked or not.
+func TestOptedInInstanceSkipsLRU(t *testing.T) {
+ s := newPCScene(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/p" {
+ pageOK(pcBody)(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html")
+ w.Header().Set("Cache-Control", "public, max-age=600")
+ io.WriteString(w, "plain "+r.URL.Path)
+ })
+ // Before the mark, the LRU is today's.
+ s.get("/q")
+ if rec := s.get("/q"); rec.Body.String() != "plain /q" || s.b.n.Load() != 1 {
+ t.Fatalf("before the mark the LRU did not serve /q (app saw %d)", s.b.n.Load())
+ }
+ wantCache(t, s.get("/p"), "miss")
+ if !s.idx.OptedIn(s.scope()) {
+ t.Fatal("not opted in")
+ }
+ lru := s.lruLen()
+ before := s.b.n.Load()
+ for _, p := range []string{"/q", "/r", "/r"} {
+ rec := s.get(p)
+ wantCache(t, rec, "bypass")
+ wantBody(t, rec, 200, "plain "+p)
+ }
+ if n := s.b.n.Load() - before; n != 3 {
+ t.Fatalf("the app saw %d of 3 requests: the LRU answered an opted-in instance", n)
+ }
+ if n := s.lruLen(); n != lru {
+ t.Fatalf("the LRU grew from %d to %d entries for an opted-in instance", lru, n)
+ }
+}
+
+// ---- path routing (P1-6) ---------------------------------------------------
+
+func TestPagePathRoutedHostRefused(t *testing.T) {
+ const front = "front.example.com"
+ var s *pcScene
+ s = newPCScene(t, pageOK(pcBody))
+ if err := s.reg.Upsert(registry.Route{Host: front, Kind: "instance", Addr: s.b.srv.Listener.Addr().String(),
+ Status: "ready", Account: "abc", App: "front", Version: pcBuild}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.reg.UpsertPath(registry.RoutePath{Host: front, Prefix: "blog", Target: pcHost}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ s.publishFor(registry.Route{Host: front, Version: pcBuild})
+ for _, path := range []string{"/blog/x", "/elsewhere"} {
+ for i := 0; i < 2; i++ {
+ rec := s.do(http.MethodGet, "http://"+front+path)
+ wantBody(t, rec, 200, pcBody)
+ wantCache(t, rec, "bypass")
+ }
+ }
+ if n := s.b.n.Load(); n != 4 {
+ t.Fatalf("the app saw %d of 4 requests", n)
+ }
+ s.wantNothingStored("a path-routed host")
+ // The target's own hostname is not path-routed and caches.
+ wantCache(t, s.get("/blog/x"), "miss")
+ wantCache(t, s.get("/blog/x"), "hit")
+}
+
+// ---- asset prefixes (P2-9, R2-5) -------------------------------------------
+
+func TestPageAssetPrefixWinsWhenAssetsOff(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody), func(r *registry.Route) { r.AssetsOff = true })
+ wantPageRefused(t, s, "/assets/app.css", 200, pcBody, "bypass")
+ wantCache(t, s.get("/p"), "miss")
+ wantCache(t, s.get("/p"), "hit")
+}
+
+func TestPageDeclarationsLoadInBackground(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody), func(r *registry.Route) { r.AssetsOff = true })
+ s.decl.forget(pcBuild)
+ wantCache(t, s.get("/p"), "bypass")
+ s.wantNothingStored("unknown declarations")
+ if n := s.decl.reads.Load(); n != 0 {
+ t.Fatalf("%d declaration reads happened on the request path", n)
+ }
+ if w := s.decl.wanted(); !slices.Contains(w, pcHost+" "+pcBuild) {
+ t.Fatalf("the request queued no background read (wanted %q)", w)
+ }
+ s.decl.load(pcBuild, "/assets/") // the background read
+ wantCache(t, s.get("/p"), "miss")
+ wantCache(t, s.get("/p"), "hit")
+ for i := 0; i < 2; i++ {
+ wantCache(t, s.get("/assets/x"), "bypass")
+ }
+ if n := s.pages(); n != 1 {
+ t.Fatalf("%d pages stored, want only /p", n)
+ }
+ if n := s.decl.reads.Load(); n != 1 {
+ t.Fatalf("%d declaration reads, want the one background read", n)
+ }
+}
+
+// ---- diagnostics (P2-10, R2-6, R3-7) ---------------------------------------
+
+func TestPageDiagnostics(t *testing.T) {
+ // /p answers a marked page; anything else an unmarked cacheable one.
+ app := func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/p" {
+ pageOK(pcBody)(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html")
+ w.Header().Set("Cache-Control", "public, max-age=600")
+ io.WriteString(w, "plain")
+ }
+ optIn := func(t *testing.T, s *pcScene) {
+ t.Helper()
+ wantCache(t, s.get("/p"), "miss")
+ }
+ for _, c := range []struct {
+ name string
+ run func(t *testing.T, s *pcScene) *httptest.ResponseRecorder
+ want string
+ }{
+ {"hit", func(t *testing.T, s *pcScene) *httptest.ResponseRecorder {
+ optIn(t, s)
+ return s.get("/p")
+ }, "hit"},
+ {"stored miss", func(t *testing.T, s *pcScene) *httptest.ResponseRecorder {
+ return s.get("/p")
+ }, "miss"},
+ {"cookie-rejected lookup", func(t *testing.T, s *pcScene) *httptest.ResponseRecorder {
+ optIn(t, s)
+ return s.get("/p", "Cookie", "session=1")
+ }, "bypass"},
+ {"first marked POST", func(t *testing.T, s *pcScene) *httptest.ResponseRecorder {
+ rec := s.do(http.MethodPost, "http://"+pcHost+"/p")
+ if s.idx.OptedIn(s.scope()) {
+ t.Fatal("a POST opted the instance in")
+ }
+ return rec
+ }, "bypass"},
+ {"marked GET, inputs unknown", func(t *testing.T, s *pcScene) *httptest.ResponseRecorder {
+ s.inputsUnknown.Store(true)
+ return s.get("/p")
+ }, "bypass"},
+ {"HEAD miss", func(t *testing.T, s *pcScene) *httptest.ResponseRecorder {
+ return s.do(http.MethodHead, "http://"+pcHost+"/p")
+ }, "bypass"},
+ {"opted in, temporarily ineligible", func(t *testing.T, s *pcScene) *httptest.ResponseRecorder {
+ optIn(t, s)
+ s.decl.forget(pcBuild)
+ return s.get("/plain")
+ }, "bypass"},
+ {"opted in, unmarked", func(t *testing.T, s *pcScene) *httptest.ResponseRecorder {
+ optIn(t, s)
+ return s.get("/plain")
+ }, "bypass"},
+ {"unarmed, marked GET", func(t *testing.T, s *pcScene) *httptest.ResponseRecorder {
+ s.e.EnablePageCache(nil)
+ rec := s.get("/p")
+ s.wantNothingStored("an unarmed box")
+ return rec
+ }, "bypass"},
+ {"unarmed, marked POST", func(t *testing.T, s *pcScene) *httptest.ResponseRecorder {
+ s.e.EnablePageCache(nil)
+ return s.do(http.MethodPost, "http://"+pcHost+"/p")
+ }, "bypass"},
+ {"unrelated app", func(t *testing.T, s *pcScene) *httptest.ResponseRecorder {
+ return s.get("/plain")
+ }, ""},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ s := newPCScene(t, app)
+ rec := c.run(t, s)
+ if got, ok := rec.Header()[assetCacheHeader]; c.want == "" && ok {
+ t.Fatalf("Carlos-Cache = %q, want none", got)
+ }
+ if c.want != "" {
+ wantCache(t, rec, c.want)
+ }
+ if rec.Code != 200 {
+ t.Fatalf("status %d", rec.Code)
+ }
+ })
+ }
+}
+
+// ---- the account throttle (R3-9) -------------------------------------------
+
+func TestPageThrottledAccountBypasses(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody))
+ wantCache(t, s.get("/p"), "miss")
+ wantCache(t, s.get("/p"), "hit")
+ s.e.SetPlanThrottleFor(func(rt registry.Route) (plans.Throttle, bool) {
+ return plans.Throttle{Bandwidth: true, Until: time.Now().Add(time.Hour)}, true
+ })
+ rec := s.get("/p")
+ wantBody(t, rec, 200, pcBody) // a token let it through planThrottleAdmit
+ wantCache(t, rec, "bypass")
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("a throttled account was served a stored page (app saw %d)", n)
+ }
+ wantCache(t, s.get("/q"), "bypass")
+ if n := s.pages(); n != 1 {
+ t.Fatalf("a throttled account's page was stored (%d pages)", n)
+ }
+}
+
+// ---- ineligible routes -----------------------------------------------------
+
+func TestPageIneligibleRoutes(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody))
+ base, ok := s.e.current()[pcHost]
+ if !ok {
+ t.Fatal("no upstream")
+ }
+ if in, ok := s.e.pageRouteEligible(pcHost, "/p", base); !ok || in != s.inputs() {
+ t.Fatalf("the base route is not eligible: %q %v", in, ok)
+ }
+ for _, c := range []struct {
+ name string
+ mod func(up *upstream)
+ path string
+ }{
+ {"static", func(up *upstream) { up.route.Kind = "static" }, "/p"},
+ {"status", func(up *upstream) { up.route.Kind = "status" }, "/p"},
+ {"forward", func(up *upstream) { up.route.Kind = registry.KindForward }, "/p"},
+ {"sidecar", func(up *upstream) { up.route.Kind = "sidecar" }, "/p"},
+ {"HA", func(up *upstream) { up.route.HA = true }, "/p"},
+ {"unit-backed", func(up *upstream) { up.route.Backing = registry.BackingUnit }, "/p"},
+ {"not ready", func(up *upstream) { up.route.Status = "stopped" }, "/p"},
+ {"gated", func(up *upstream) { up.route.Gate = "$2a$hash" }, "/p"},
+ {"import gate", func(up *upstream) { up.route.ImportGate = "import-1" }, "/p"},
+ {"pages off", func(up *upstream) { up.route.PagesOff = true }, "/p"},
+ {"via tunnel", func(up *upstream) { up.viaTunnel = true }, "/p"},
+ {"another route's dispatch", func(up *upstream) { up.route.Host = "other.example.com" }, "/p"},
+ {"declared prefix", func(up *upstream) {}, "/assets/x"},
+ {"undeclared build", func(up *upstream) { up.route.Version = "v9" }, "/p"},
+ {"no build", func(up *upstream) { up.route.Version = "" }, "/p"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ up := base
+ c.mod(&up)
+ if in, ok := s.e.pageRouteEligible(pcHost, c.path, up); ok {
+ t.Fatalf("eligible with inputs %q", in)
+ }
+ })
+ }
+ t.Run("inputs unknown", func(t *testing.T) {
+ s.inputsUnknown.Store(true)
+ defer s.inputsUnknown.Store(false)
+ if _, ok := s.e.pageRouteEligible(pcHost, "/p", base); ok {
+ t.Fatal("eligible with unknown inputs")
+ }
+ })
+ t.Run("throttled", func(t *testing.T) {
+ s.e.SetPlanThrottleFor(func(registry.Route) (plans.Throttle, bool) { return plans.Throttle{Awake: true}, true })
+ defer s.e.SetPlanThrottleFor(nil)
+ if _, ok := s.e.pageRouteEligible(pcHost, "/p", base); ok {
+ t.Fatal("eligible while the account is throttled")
+ }
+ })
+ t.Run("no asset state", func(t *testing.T) {
+ st := s.e.assets.Swap(nil)
+ defer s.e.assets.Store(st)
+ if _, ok := s.e.pageRouteEligible(pcHost, "/p", base); ok {
+ t.Fatal("eligible with no asset state")
+ }
+ })
+ t.Run("a policy without declarations", func(t *testing.T) {
+ st := s.e.assets.Load()
+ s.e.assets.Store(&assetState{store: st.store, local: &st.local.(*pcDecl).fakeLocalAssets, now: time.Now})
+ defer s.e.assets.Store(st)
+ if _, ok := s.e.pageRouteEligible(pcHost, "/p", base); ok {
+ t.Fatal("eligible with no declarations source")
+ }
+ })
+ t.Run("unarmed", func(t *testing.T) {
+ s.e.EnablePageCache(nil)
+ defer s.e.EnablePageCache(s.idx)
+ if _, ok := s.e.pageRouteEligible(pcHost, "/p", base); ok {
+ t.Fatal("eligible on an unarmed box")
+ }
+ })
+ if _, ok := s.e.pageRouteEligible(pcHost, "/p", base); !ok {
+ t.Fatal("the base route is not eligible after the table")
+ }
+}
diff --git a/internal/edge/pagerecord.go b/internal/edge/pagerecord.go
new file mode 100644
index 000000000..bdf407e08
--- /dev/null
+++ b/internal/edge/pagerecord.go
@@ -0,0 +1,164 @@
+package edge
+
+import (
+ "fmt"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/assetcache"
+ "github.com/carlosframework/platform/internal/pageindex"
+)
+
+// pageRecorder wraps every proxied response of an instance route at the LRU
+// point (pageServe.wrap), on every box, armed or not.
+//
+// As the diagnostic writer it sets Carlos-Cache at the first final status
+// when the instance is opted in or the response is marked (P2-10, R2-6,
+// R3-7): "miss" when the response is being recorded into the page index,
+// "bypass" otherwise. On an unarmed box only the marker can set it, and it
+// is always "bypass".
+//
+// As the recorder, for a request being recorded (pageServe.storing), it
+// reserves a page at that status when pageAdmit keeps the response and its
+// Content-Length (when present) is at most pageindex.MaxBody, then tees the
+// body into the reservation while passing every byte on. A body that grows
+// past MaxBody, or a reservation write that fails, abandons the recording
+// and the rest streams on unrecorded. finish publishes it, or abandons it.
+//
+// It runs on the request's goroutine only: the proxy writes it, and finish
+// runs after the proxy has returned.
+type pageRecorder struct {
+ http.ResponseWriter
+ ps *pageServe
+
+ wrote bool
+ snap http.Header // the final status's headers, before Carlos-Cache
+ lifetime time.Duration
+ cl int64 // the declared Content-Length, -1 when none
+ n int64 // body bytes passed on
+ failed bool // a write to the client failed: the body may be short
+ pend *pageindex.Pending
+}
+
+func (p *pageRecorder) WriteHeader(code int) {
+ if code < 200 || p.wrote {
+ p.ResponseWriter.WriteHeader(code)
+ return
+ }
+ p.wrote = true
+ ps := p.ps
+ h := p.Header()
+ mark := pageMarkOf(ps.r)
+ if ps.storing {
+ p.snap = h.Clone()
+ if life, ok := pageAdmit(code, h, mark); ok {
+ if cl, ok := pageContentLength(h); ok && cl <= pageindex.MaxBody {
+ if pend, err := ps.x.Reserve(ps.ticket, ps.key, cl); err == nil {
+ p.pend, p.lifetime, p.cl = pend, life, cl
+ }
+ }
+ }
+ }
+ if ps.optedIn || (mark != nil && mark.Marked) {
+ result := "bypass"
+ if p.pend != nil {
+ result = "miss"
+ }
+ h.Set(assetCacheHeader, result)
+ }
+ p.ResponseWriter.WriteHeader(code)
+}
+
+// pageContentLength reads h's Content-Length: -1 when there is none, false
+// when it is not one non-negative decimal.
+func pageContentLength(h http.Header) (int64, bool) {
+ vs := h.Values("Content-Length")
+ if len(vs) == 0 {
+ return -1, true
+ }
+ if len(vs) != 1 {
+ return 0, false
+ }
+ n, err := strconv.ParseInt(strings.TrimSpace(vs[0]), 10, 64)
+ if err != nil || n < 0 {
+ return 0, false
+ }
+ return n, true
+}
+
+func (p *pageRecorder) Write(b []byte) (int, error) {
+ if !p.wrote {
+ p.WriteHeader(http.StatusOK)
+ }
+ if p.pend != nil {
+ if _, err := p.pend.Write(b); err != nil {
+ // Past MaxBody or the reservation, or a disk error: the rest
+ // goes to the visitor unrecorded.
+ p.abort()
+ }
+ }
+ n, err := p.ResponseWriter.Write(b)
+ p.n += int64(n)
+ if err != nil {
+ p.failed = true
+ }
+ return n, err
+}
+
+func (p *pageRecorder) Flush() {
+ if !p.wrote {
+ p.WriteHeader(http.StatusOK)
+ }
+ _ = http.NewResponseController(p.ResponseWriter).Flush()
+}
+
+func (p *pageRecorder) Unwrap() http.ResponseWriter { return p.ResponseWriter }
+
+// abort abandons the recording, if one runs.
+func (p *pageRecorder) abort() {
+ if p.pend != nil {
+ p.pend.Abort()
+ p.pend = nil
+ }
+}
+
+// finish publishes the recorded page once the proxy has returned, or
+// abandons it: on a body shorter than its Content-Length or a failed client
+// write, on a Set-Cookie trailer (announced or not), and when the route, its
+// current inputs or its process's inputs are no longer the ones the
+// recording began with. Before publishing it makes the instance's opt-in
+// mark durable (the LRU is off for the instance from then on); the page is
+// stored under assetStoredHeader with its lifetime from now, and the
+// marker's ignorable cookies.
+func (p *pageRecorder) finish() {
+ pend := p.pend
+ if pend == nil {
+ return
+ }
+ p.pend = nil
+ ps := p.ps
+ if !p.wrote || p.failed || (p.cl >= 0 && p.n != p.cl) ||
+ assetTrailerVeto(assetTrailers(p.snap, p.Header())) || !ps.stillCurrent() {
+ pend.Abort()
+ return
+ }
+ if err := ps.x.MarkOptIn(ps.scope); err != nil {
+ pend.Abort()
+ ps.e.logThrottled("page-mark "+ps.up.route.Host, fmt.Sprintf(
+ "page cache: could not record the opt-in of %s, so its page was not stored: %v", ps.up.route.Host, err))
+ return
+ }
+ var ignore []string
+ if m := pageMarkOf(ps.r); m != nil {
+ ignore = m.Ignore
+ }
+ now := ps.e.pageClock()
+ _, err := pend.Finish(assetcache.Meta{Header: assetStoredHeader(p.snap), Lifetime: p.lifetime, Expires: now.Add(p.lifetime)}, ignore)
+ if err != nil {
+ pend.Abort()
+ ps.e.logThrottled("page-commit "+ps.up.route.Host, fmt.Sprintf(
+ "page cache: storing %s%s for %s failed: %v", ps.key.Host, ps.key.Path, ps.up.route.Host, err))
+ }
+}
diff --git a/internal/host/assetmanifests.go b/internal/host/assetmanifests.go
index 4860a326f..9df983f92 100644
--- a/internal/host/assetmanifests.go
+++ b/internal/host/assetmanifests.go
@@ -38,8 +38,12 @@ func assetManifestKey(acct, app, version string) string {
// paths answers build version of acct/app's declared asset paths, reading the
// bucket if it has not been read yet. False when the read fails; a build that
// declares nothing answers no paths and true. An empty version names no build
-// and answers no paths without a read.
+// and answers no paths without a read. A nil cache (not bound yet) reads
+// nothing and answers false.
func (c *assetManifestCache) paths(ctx context.Context, acct, app, version string) ([]string, bool) {
+ if c == nil {
+ return nil, false
+ }
if version == "" {
return nil, true
}
@@ -60,16 +64,24 @@ func (c *assetManifestCache) paths(ctx context.Context, acct, app, version strin
return slices.Clone(p), true
}
-// cached is paths without a read: false when the build has not been read.
+// cached is paths without a read: false when the build has not been read,
+// or the cache is nil.
func (c *assetManifestCache) cached(acct, app, version string) ([]string, bool) {
+ if c == nil {
+ return nil, false
+ }
c.mu.Lock()
defer c.mu.Unlock()
p, ok := c.byKey[assetManifestKey(acct, app, version)]
return slices.Clone(p), ok
}
-// prune drops every build whose assetManifestKey is not in keep.
+// prune drops every build whose assetManifestKey is not in keep. A nil
+// cache holds nothing to drop.
func (c *assetManifestCache) prune(keep map[string]bool) {
+ if c == nil {
+ return
+ }
c.mu.Lock()
defer c.mu.Unlock()
for k := range c.byKey {
@@ -79,8 +91,12 @@ func (c *assetManifestCache) prune(keep map[string]bool) {
}
}
-// all is a copy of every build held, by assetManifestKey.
+// all is a copy of every build held, by assetManifestKey; nil for a nil
+// cache.
func (c *assetManifestCache) all() map[string][]string {
+ if c == nil {
+ return nil
+ }
c.mu.Lock()
defer c.mu.Unlock()
out := make(map[string][]string, len(c.byKey))
diff --git a/internal/host/assetpolicy.go b/internal/host/assetpolicy.go
index de306cf0e..4b612591d 100644
--- a/internal/host/assetpolicy.go
+++ b/internal/host/assetpolicy.go
@@ -6,8 +6,10 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
+ "log"
"slices"
"strings"
+ "sync"
"sync/atomic"
"time"
@@ -96,9 +98,13 @@ func edgesChangeKey(fp, servingDigest string) string {
// edge.LocalAssets. The writer's own state (written, knownAt) is touched only
// by the edges file loop's goroutine.
type assetPolicy struct {
- reg *registry.Registry
- auth *assetAuthority
- manifests *assetManifestCache
+ reg *registry.Registry
+ auth *assetAuthority
+ // manifests is the manifest cache, published once by bindManifests (or
+ // at construction). Nil until then: the agent hands the policy to the
+ // edge before the edges file loop has opened its store, so requests may
+ // ask DeclaresPrefix before the bind (R3-6).
+ manifests atomic.Pointer[assetManifestCache]
serving servingBuild
// written is the block this process last wrote for each host, with the
@@ -122,6 +128,15 @@ type assetPolicy struct {
// only by the edges file writer.
snap atomic.Pointer[assetSnapshot]
+ // The page cache's background declaration reads (DeclaresPrefix,
+ // WantDeclarations): the builds waiting to be read, keyed by
+ // assetManifestKey; when each failed read may be tried again; and
+ // whether the loader goroutine is running. All under wantMu.
+ wantMu sync.Mutex
+ wantQueue map[string]wantedBuild
+ wantFailed map[string]time.Time
+ wantRunning bool
+
// publishing gates the whole policy for the writer (active): false until
// the ready hook has opened this box's asset store and armed its edge
// (armEdgeAssetCache), so an edges file never advertises a home that
@@ -146,7 +161,11 @@ func armAssetPolicy(getenv func(string) string, reg *registry.Registry, auth *as
if sb == nil {
sb = noServingBuild
}
- return &assetPolicy{reg: reg, auth: auth, manifests: manifests, serving: sb, written: map[string]writtenAssets{}}
+ p := &assetPolicy{reg: reg, auth: auth, serving: sb, written: map[string]writtenAssets{}}
+ if manifests != nil {
+ p.manifests.Store(manifests)
+ }
+ return p
}
// allowPublication opens the writer's gate (active): the box's asset store
@@ -173,12 +192,13 @@ func (p *assetPolicy) active() *assetPolicy {
// 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.
+// pass. For, Declared and AssetsReady never touch it; DeclaresPrefix and
+// the background declaration loader read it through the atomic pointer, so
+// the edge may already be calling them, and answers unknown until the bind
+// (R3-6). A policy that already has a cache keeps it.
func (p *assetPolicy) bindManifests(c *assetManifestCache) {
- if p != nil && p.manifests == nil {
- p.manifests = c
+ if p != nil && c != nil {
+ p.manifests.CompareAndSwap(nil, c)
}
}
@@ -335,7 +355,7 @@ func (p *assetPolicy) decide(ctx context.Context, in assetInputs, clocks assetCl
}
var paths []string
for _, b := range builds {
- bp, ok := p.manifests.paths(ctx, acct, app, b)
+ bp, ok := p.manifests.Load().paths(ctx, acct, app, b)
if !ok {
continue // that build publishes no paths until it can be read
}
@@ -418,15 +438,155 @@ func (p *assetPolicy) Declared(host, build, path string) bool {
return slices.ContainsFunc(paths, func(prefix string) bool { return strings.HasPrefix(path, prefix) })
}
+// assetDeclarationsQueueMax bounds the builds waiting for a background
+// declaration read; a build asked for while it is full is asked again by a
+// later request.
+const assetDeclarationsQueueMax = 64
+
+// assetDeclarationsRetry is how long a build whose declaration read failed
+// waits before a request may queue it again, so a missing manifest is not
+// read at the request rate.
+const assetDeclarationsRetry = time.Minute
+
+// assetDeclarationsReadTimeout bounds one background manifest read.
+const assetDeclarationsReadTimeout = 30 * time.Second
+
+// wantedBuild is one build waiting for a background declaration read.
+type wantedBuild struct{ acct, app, build string }
+
+var _ interface {
+ DeclaresPrefix(host, build, path string) (declared, known bool)
+} = (*assetPolicy)(nil)
+
+// DeclaresPrefix reports whether build, run by the route host, declares an
+// asset prefix of path (the page cache's rule, edge page cache plan 1 Task 7,
+// P2-9 and R2-5): declared prefixes belong to the asset cache, so a page
+// under one is never stored. known is false when the answer is not held: the
+// manifest cache is not bound yet (R3-6), the settled snapshot does not name
+// host's owner, build is empty, or the build's manifest has not been read.
+// In the last case it queues a background read (WantDeclarations), so a
+// later request knows. It reads only the manifest cache and the snapshot,
+// never the bucket, and AssetsOff does not change its answer. Safe for
+// concurrent calls.
+func (p *assetPolicy) DeclaresPrefix(host, build, path string) (declared, known bool) {
+ if p == nil || build == "" {
+ return false, false
+ }
+ c := p.manifests.Load()
+ s := p.current()
+ if c == nil || s == nil {
+ return false, false
+ }
+ o, ok := s.owners[host]
+ if !ok {
+ return false, false
+ }
+ paths, ok := c.cached(o.account, o.app, build)
+ if !ok {
+ p.WantDeclarations(o.account, o.app, build)
+ return false, false
+ }
+ return slices.ContainsFunc(paths, func(prefix string) bool { return prefix != "" && strings.HasPrefix(path, prefix) }), true
+}
+
+// WantDeclarations queues a background read of acct/app build's manifest
+// into the manifest cache, on the policy's own goroutine, never the caller's.
+// A build already held, already queued, or whose last read failed within
+// assetDeclarationsRetry is not queued again, and the queue holds at most
+// assetDeclarationsQueueMax builds.
+func (p *assetPolicy) WantDeclarations(acct, app, build string) {
+ if p == nil || build == "" {
+ return
+ }
+ c := p.manifests.Load()
+ if c == nil {
+ return
+ }
+ if _, ok := c.cached(acct, app, build); ok {
+ return
+ }
+ k := assetManifestKey(acct, app, build)
+ now := time.Now()
+ p.wantMu.Lock()
+ defer p.wantMu.Unlock()
+ if until, ok := p.wantFailed[k]; ok {
+ if now.Before(until) {
+ return
+ }
+ delete(p.wantFailed, k)
+ }
+ if _, ok := p.wantQueue[k]; ok || len(p.wantQueue) >= assetDeclarationsQueueMax {
+ return
+ }
+ if p.wantQueue == nil {
+ p.wantQueue = map[string]wantedBuild{}
+ }
+ p.wantQueue[k] = wantedBuild{acct: acct, app: app, build: build}
+ if !p.wantRunning {
+ p.wantRunning = true
+ go p.loadDeclarations(c)
+ }
+}
+
+// loadDeclarations reads the queued builds' manifests into c one at a time,
+// and returns when the queue is empty. A build stays in the queue while it
+// is read, so it is not queued twice; a failed read is remembered for
+// assetDeclarationsRetry.
+func (p *assetPolicy) loadDeclarations(c *assetManifestCache) {
+ for {
+ p.wantMu.Lock()
+ var k string
+ var w wantedBuild
+ for k, w = range p.wantQueue {
+ break
+ }
+ if k == "" {
+ p.wantRunning = false
+ p.wantMu.Unlock()
+ return
+ }
+ p.wantMu.Unlock()
+
+ ctx, cancel := context.WithTimeout(context.Background(), assetDeclarationsReadTimeout)
+ _, ok := c.paths(ctx, w.acct, w.app, w.build)
+ cancel()
+
+ now := time.Now()
+ p.wantMu.Lock()
+ delete(p.wantQueue, k)
+ if !ok {
+ if p.wantFailed == nil {
+ p.wantFailed = map[string]time.Time{}
+ }
+ for fk, until := range p.wantFailed {
+ if !now.Before(until) {
+ delete(p.wantFailed, fk)
+ }
+ }
+ p.wantFailed[k] = now.Add(assetDeclarationsRetry)
+ }
+ p.wantMu.Unlock()
+ if !ok {
+ log.Printf("agent: page cache: could not read the asset declarations of %s %s build %s; its pages are not cached until a later read works", w.acct, w.app, w.build)
+ }
+ }
+}
+
// assetSnapshot is one settled decision for every hostname this box could
// catch for itself: For's answers (pooled routes included, aliases whatever
// their DNS) and the declared paths of every build the manifest cache held.
-// It is immutable once published.
+// owners is every ready, non-sidecar route host's owner, whether or not it
+// catches assets: DeclaresPrefix names a build's manifest by it. It is
+// immutable once published.
type assetSnapshot struct {
hosts map[string]edge.HostAssets
builds map[string][]string
+ owners map[string]assetOwner
}
+// assetOwner is the account and app a route's manifests are read under.
+type assetOwner struct{ account, app string }
+
// current is the snapshot For and Declared answer from: the writer's last
// settled decision. Nil until the edges file writer has stored its first one,
// and until then the home catches nothing (design §4.2, "after a restart";
@@ -443,7 +603,12 @@ func (p *assetPolicy) current() *assetSnapshot {
// writer's schedule. The caller has checked that in was read settled against
// clocks.
func (p *assetPolicy) buildSnapshot(ctx context.Context, in assetInputs, clocks assetClocks) *assetSnapshot {
- s := &assetSnapshot{hosts: map[string]edge.HostAssets{}}
+ s := &assetSnapshot{hosts: map[string]edge.HostAssets{}, owners: map[string]assetOwner{}}
+ for host, r := range in.byHost {
+ if r.Status == "ready" && !r.IsSidecar() {
+ s.owners[host] = assetOwner{account: release.RouteAccount(r), app: r.App}
+ }
+ }
consider := func(host string) {
if _, done := s.hosts[host]; done {
return
@@ -458,7 +623,7 @@ func (p *assetPolicy) buildSnapshot(ctx context.Context, in assetInputs, clocks
for alias := range in.aliasOf {
consider(alias)
}
- s.builds = p.manifests.all()
+ s.builds = p.manifests.Load().all()
return s
}
diff --git a/internal/host/assetpolicy_test.go b/internal/host/assetpolicy_test.go
new file mode 100644
index 000000000..0b5219fc8
--- /dev/null
+++ b/internal/host/assetpolicy_test.go
@@ -0,0 +1,226 @@
+package host
+
+import (
+ "context"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The page cache's view of the asset declarations (edge page cache plan 1,
+// Task 7, R2-5 and R3-6): DeclaresPrefix answers from the manifest cache
+// alone, never a bucket read on the request, whatever AssetsOff says, and
+// queues a background read for a build it has not read.
+
+// gatedGetStore blocks every Get until open is called, and counts them, so a
+// test can tell a read on the caller's goroutine (which would block) from a
+// background one.
+type gatedGetStore struct {
+ release.Store
+ gate chan struct{}
+ once sync.Once
+ gets atomic.Int64
+}
+
+func newGatedGetStore(s release.Store) *gatedGetStore {
+ return &gatedGetStore{Store: s, gate: make(chan struct{})}
+}
+
+func (g *gatedGetStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ g.gets.Add(1)
+ select {
+ case <-g.gate:
+ case <-ctx.Done():
+ return nil, "", ctx.Err()
+ }
+ return g.Store.Get(ctx, key)
+}
+
+func (g *gatedGetStore) open() { g.once.Do(func() { close(g.gate) }) }
+
+// declaresWithin calls DeclaresPrefix on another goroutine and fails if it
+// does not return within a second: a request-time bucket read would block on
+// the gated store.
+func declaresWithin(t *testing.T, p *assetPolicy, host, build, path string) (declared, known bool) {
+ t.Helper()
+ type answer struct{ declared, known bool }
+ ch := make(chan answer, 1)
+ go func() {
+ d, k := p.DeclaresPrefix(host, build, path)
+ ch <- answer{d, k}
+ }()
+ select {
+ case a := <-ch:
+ return a.declared, a.known
+ case <-time.After(time.Second):
+ t.Fatalf("DeclaresPrefix(%s, %s, %s) blocked: it read the bucket on the request", host, build, path)
+ return false, false
+ }
+}
+
+// waitDeclared polls DeclaresPrefix until it knows the answer.
+func waitDeclared(t *testing.T, p *assetPolicy, host, build, path string) (declared bool) {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ if d, k := p.DeclaresPrefix(host, build, path); k {
+ return d
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("DeclaresPrefix(%s, %s, %s) never became known", host, build, path)
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+}
+
+// An assets-off instance's build is read in the background, so it goes from
+// unknown to known without any read on the request path; the answer is the
+// build's declaration whatever AssetsOff says, the same as for an instance
+// that catches assets, and concurrent asks read the manifest once.
+func TestDeclaresPrefixIgnoresAssetsOff(t *testing.T) {
+ for _, assetsOff := range []bool{true, false} {
+ name := "assets-on"
+ if assetsOff {
+ name = "assets-off"
+ }
+ t.Run(name, func(t *testing.T) {
+ w := newAssetWorld(t)
+ gated := newGatedGetStore(w.store)
+ w.cache = newAssetManifestCache(gated)
+ w.policy = armAssetPolicy(armedAssetEnv, w.reg, w.auth, w.cache, w.servingBuild)
+ w.policy.allowPublication()
+ w.ship("v1", "/assets/")
+ w.instance("shop.example.com", assetGen1, "v1", func(r *registry.Route) { r.AssetsOff = assetsOff })
+ w.confirm()
+ if !assetsOff {
+ // The writer's own pass reads an asset-catching build's
+ // manifest itself; let it, so the ask below is the cache's.
+ gated.open()
+ }
+ w.pass()
+ if !assetsOff {
+ if got := waitDeclared(t, w.policy, "shop.example.com", "v1", "/assets/app.js"); !got {
+ t.Fatal("an asset-catching build's prefix is not declared")
+ }
+ return
+ }
+ if n := gated.gets.Load(); n != 0 {
+ t.Fatalf("the writer read %d objects for an assets-off build; the test assumes it reads none", n)
+ }
+ for i := 0; i < 10; i++ {
+ if _, known := declaresWithin(t, w.policy, "shop.example.com", "v1", "/assets/app.js"); known {
+ t.Fatal("an unread build's declaration was known")
+ }
+ }
+ gated.open()
+ if !waitDeclared(t, w.policy, "shop.example.com", "v1", "/assets/app.js") {
+ t.Fatal("an assets-off build's declared prefix is not declared")
+ }
+ if d, k := w.policy.DeclaresPrefix("shop.example.com", "v1", "/p"); !k || d {
+ t.Fatalf("an undeclared path = (%v, %v), want (false, true)", d, k)
+ }
+ if n := gated.gets.Load(); n != 1 {
+ t.Fatalf("the manifest was read %d times, want once", n)
+ }
+ // An unknown host and an empty build stay unknown, and queue
+ // nothing that reads.
+ if _, k := w.policy.DeclaresPrefix("other.example.com", "v1", "/p"); k {
+ t.Fatal("a host the snapshot does not hold was known")
+ }
+ if _, k := w.policy.DeclaresPrefix("shop.example.com", "", "/p"); k {
+ t.Fatal("an empty build was known")
+ }
+ })
+ }
+}
+
+// Requests ask DeclaresPrefix while the edges file loop binds the manifest
+// cache late (R3-6). Before the bind every answer is unknown, nothing
+// panics, and the race detector sees the publication as ordered.
+func TestDeclaresPrefixBeforeBindIsUnknown(t *testing.T) {
+ w := newAssetWorld(t)
+ w.policy = armAssetPolicy(armedAssetEnv, w.reg, w.auth, nil, w.servingBuild)
+ w.policy.allowPublication()
+ w.ship("v1", "/assets/")
+ w.instance("shop.example.com", assetGen1, "v1", func(r *registry.Route) { r.AssetsOff = true })
+ w.confirm()
+ w.pass() // a pass with no manifest cache publishes its snapshot all the same
+
+ var bound atomic.Bool
+ stop := make(chan struct{})
+ var wg sync.WaitGroup
+ var knownBeforeBind atomic.Int64
+ for i := 0; i < 8; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+ wasBound := bound.Load()
+ if _, k := w.policy.DeclaresPrefix("shop.example.com", "v1", "/assets/app.js"); k && !wasBound {
+ knownBeforeBind.Add(1)
+ }
+ }
+ }()
+ }
+ time.Sleep(20 * time.Millisecond)
+ w.policy.bindManifests(newAssetManifestCache(w.store))
+ bound.Store(true)
+ if !waitDeclared(t, w.policy, "shop.example.com", "v1", "/assets/app.js") {
+ t.Fatal("after the bind the declared prefix is not declared")
+ }
+ close(stop)
+ wg.Wait()
+ if n := knownBeforeBind.Load(); n != 0 {
+ t.Fatalf("%d answers before the bind were known", n)
+ }
+ // A second bind changes nothing: the first cache stays.
+ first := w.policy.manifests.Load()
+ w.policy.bindManifests(newAssetManifestCache(w.store))
+ if w.policy.manifests.Load() != first {
+ t.Fatal("a second bind replaced the manifest cache")
+ }
+}
+
+// A build whose manifest cannot be read is not asked for again on every
+// request: the loader waits before retrying it, and the queue is bounded.
+func TestDeclaresPrefixFailedReadIsNotRetriedAtOnce(t *testing.T) {
+ w := newAssetWorld(t)
+ w.instance("shop.example.com", assetGen1, "v9", func(r *registry.Route) { r.AssetsOff = true })
+ w.confirm()
+ w.pass() // v9 was never shipped: its manifest read fails
+ for i := 0; i < 50; i++ {
+ if _, k := w.policy.DeclaresPrefix("shop.example.com", "v9", "/p"); k {
+ t.Fatal("an unreadable build was known")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ key := release.ManifestKey("abc", "shop", "v9")
+ deadline := time.Now().Add(5 * time.Second)
+ for w.store.getsOf(key) == 0 {
+ if time.Now().After(deadline) {
+ t.Fatal("the unreadable manifest was never read in the background")
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ if n := w.store.getsOf(key); n > 2 {
+ t.Fatalf("the unreadable manifest was read %d times in 50 asks", n)
+ }
+ for i := 0; i < 3*assetDeclarationsQueueMax; i++ {
+ w.policy.WantDeclarations("abc", "shop", "q"+string(rune('a'+i%26))+string(rune('a'+i/26)))
+ }
+ w.policy.wantMu.Lock()
+ n := len(w.policy.wantQueue)
+ w.policy.wantMu.Unlock()
+ if n > assetDeclarationsQueueMax {
+ t.Fatalf("the queue holds %d builds, want at most %d", n, assetDeclarationsQueueMax)
+ }
+}
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go
index 0bb439c3b..746bae7ae 100644
--- a/internal/host/edgesfile.go
+++ b/internal/host/edgesfile.go
@@ -944,7 +944,7 @@ func edgesFileWriteClaims(ctx context.Context, s release.Store, reg *registry.Re
hosts[host] = h
}
}
- assets.manifests.prune(assets.keepBuilds(routes))
+ assets.manifests.Load().prune(assets.keepBuilds(routes))
// The home's own catch (For, Declared) answers from the last
// settled decision; only a settled pass replaces it.
if settled {