edge: Carlos-Purge and the control socket clear pages; add the all target
Every Carlos-Purge target and every control socket body now clears the
matching pages of the page index as well as the LRU. The bare target
"all" (header and {"path":"all"}) purges the LRU of the instance's
primary and every alias and clears every page of the instance. With no
Carlos-Purge-Host, a write served on an alias also clears that alias's
pages. The socket reaches the index through a bridge on Cache that
EnableCache installs; Cache.PurgeHost, which every process start calls,
never reaches it, so a wake keeps its pages.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/edge/cache.go+41 −0internal/edge/edge.go+5 −0internal/edge/pagecache.go+58 −0internal/edge/pageclear_test.go+411 −0internal/edge/purge.go+43 −5internal/edge/purge_header.go+104 −7
Intent
<task-notification> <task-id>a7287ac9275b31cdc</task-id> <tool-use-id>toolu_01LEqnjYfcgXWYn6HJZH5HaU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/a7287ac9275b31cdc.output</output-file> <status>completed</status> <summary>Agent "Implement Task 7: home-box page serving" 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. All three review findings are fixed and every covering test passes. Commits (new, nothing amended): - `e231c7fd` edge: page diagnostics on held and upgrade answers; serving app's decls - Earlier, unchanged: `bf3bd261`, `d7bbea5d`, `871bb18c` What changed: 1. **Diagnostics before the LRU point.** Held-stream and upgrade answers now get `Carlos-Cache` by the same rule; a real 101 gets none. A held stream's first leg passes the app's marker on to the browser's response. The writer now forwards `Hijack`, which two existing upgrade tests require. 2. **Serving app's declarations.** `DeclaresPrefix` now takes the serving route's account and app from the edge (signature `DeclaresPrefix(account, app, build, path)`, interface updated), so a stale snapshot can no longer answer with the previous app's prefixes. 3. **Bind test.** Only calls made wholly before the bind must be unknown; calls across the bind may answer either way. It passed 20 runs in a row under `-race`. Tests: 3 new tests cover the fixes. The page tests, held/upgrade/rate tests and wider writer-path neighbours pass, `-race` is clean on both packages, and taking out each of the 6 fixes in turn makes a test fail. Concerns: demo-route traffic still skips the diagnostics; the review did not list it. The asset-catch paths already set their own `Carlos-Cache`, so I left them alone. Report (fix section appended): `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-page-cache-1/.superpowers/sdd/2026-11-08-edge-page-cache-plan-1-home/task-7-report.md`</result> <usage><subagent_tokens>383032</subagent_tokens><tool_uses>19</tool_uses><duration_ms>1509602</duration_ms></usage> </task-notification>
<task-notification> <task-id>bpz7tj1fq</task-id> <tool-use-id>toolu_017uvSSk8arUqX2zW6fT6Z3v</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/bpz7tj1fq.output</output-file> <status>completed</status> <summary>Background command "Run scoped Astra re-review of Task 7 fix" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 23.3 g CO₂e (3,021,339 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on edge-page-cache-1, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/edge/cache.go b/internal/edge/cache.go| index ee385503a..b492b3bed 100644 |
| --- a/internal/edge/cache.go |
| +++ b/internal/edge/cache.go |
| @@ -4,8 +4,10 @@ import ( |
| "container/list" |
| "net/http" |
| "sync" |
| + "sync/atomic" |
| "time" |
| + "github.com/carlosframework/platform/internal/pageindex" |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| @@ -90,6 +92,45 @@ type Cache struct { |
| // currentInputs answers a route's current inputs (SetCurrentInputs); |
| // nil answers none. |
| currentInputs func(registry.Route) (string, bool) |
| + |
| + // bridge reaches the edge's page index from the control socket, which |
| + // is handed this Cache and not the Edge (setBridge). Nil: no edge set |
| + // it, and the socket clears the LRU only. |
| + bridge atomic.Pointer[purgeBridgeRef] |
| +} |
| + |
| +// purgeBridge is what the control socket's POST /purge needs of the edge |
| +// beyond the LRU (page cache plan 1, Task 8). The Edge implements it, and |
| +// EnableCache installs it. Only the socket handler and the Carlos-Purge |
| +// header reach it: Cache.PurgeHost, which every process start calls, never |
| +// does, so a wake never clears a page. |
| +type purgeBridge interface { |
| + // clearPages applies c to the pages of host's instance, with host as |
| + // the one host of a per-host clear. A host the edge does not route, or |
| + // an edge with no page cache, clears nothing. |
| + clearPages(host string, c pageindex.Clear) |
| + // instanceHosts is every host the edge routes to host's instance: its |
| + // primary and every alias. Nil when host is not routed. |
| + instanceHosts(host string) []string |
| +} |
| + |
| +type purgeBridgeRef struct{ b purgeBridge } |
| + |
| +// setBridge installs b (nil removes it). |
| +func (c *Cache) setBridge(b purgeBridge) { |
| + if b == nil { |
| + c.bridge.Store(nil) |
| + return |
| + } |
| + c.bridge.Store(&purgeBridgeRef{b}) |
| +} |
| + |
| +// purgeBridgeOf is the installed bridge, or nil. |
| +func (c *Cache) purgeBridgeOf() purgeBridge { |
| + if r := c.bridge.Load(); r != nil { |
| + return r.b |
| + } |
| + return nil |
| } |
| type cacheURLKey struct { |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index fd067f75f..dac09aebe 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -650,6 +650,11 @@ func (e *Edge) EnableStatic(store release.Store, pub ed25519.PublicKey, cacheDir |
| // existing nil-means-disabled convention for Activator. |
| func (e *Edge) EnableCache(cache *Cache) { |
| e.cache = cache |
| + // The control socket is handed the Cache, not the Edge: this is how its |
| + // purges reach the page index (purgeBridge). |
| + if cache != nil { |
| + cache.setBridge(e) |
| + } |
| // The generation guard (spec §7.2), only with generations on: e.gens is |
| // nil otherwise and the cache stays untagged, exactly as before. |
| if cache != nil && e.gens != nil { |
diff --git a/internal/edge/pagecache.go b/internal/edge/pagecache.go| index b0fc00852..1cf6e83ef 100644 |
| --- a/internal/edge/pagecache.go |
| +++ b/internal/edge/pagecache.go |
| @@ -2,6 +2,7 @@ package edge |
| import ( |
| "net/http" |
| + "slices" |
| "strings" |
| "time" |
| @@ -43,6 +44,63 @@ func pageScopeOf(up upstream) pageindex.Scope { |
| return pageindex.Scope{Account: release.RouteAccount(up.route), App: up.route.App, Instance: up.route.Host} |
| } |
| +// clearPages applies c to the pages of host's instance (purgeBridge): the |
| +// scope of host's entry in the live route table, so an alias or a host |
| +// served through a wildcard clears its own instance's pages. A clear with |
| +// targets is a per-host clear, of host alone; a clear with none (the "all" |
| +// target) clears every host of the scope. Nothing happens on an unarmed box |
| +// or for a host the edge does not route. |
| +// |
| +// Only the purge channels call it: the Carlos-Purge header |
| +// (applyPurgeTargets) and the control socket. A process start purges the |
| +// LRU through Cache.PurgeHost, which never reaches here, so a wake never |
| +// clears a page. |
| +func (e *Edge) clearPages(host string, c pageindex.Clear) { |
| + x := e.pages.Load() |
| + if x == nil { |
| + return |
| + } |
| + up, ok := lookupIn(e.current(), host) |
| + if !ok { |
| + return |
| + } |
| + switch { |
| + case c.Targets == nil: |
| + c.Hosts = nil |
| + case len(c.Targets) == 0: |
| + return // names nothing |
| + default: |
| + c.Hosts = []string{host} |
| + } |
| + x.Clear(pageScopeOf(up), c) |
| +} |
| + |
| +// instanceHosts is every host the live route table routes to host's |
| +// instance (purgeBridge): its primary and every alias, sorted. An entry |
| +// counts when its route is the same instance, by primary host and scope, |
| +// so another instance's entries never do. A wildcard key is a routing |
| +// pattern, not a name anything is cached under, and is left out: the hosts |
| +// served through it cannot be listed, and their LRU entries keep the TTL |
| +// ceiling (their pages are in the scope, which "all" clears whole). Nil |
| +// when host is not routed. |
| +func (e *Edge) instanceHosts(host string) []string { |
| + m := e.current() |
| + own, ok := lookupIn(m, host) |
| + if !ok || own.route.Host == "" { |
| + return nil |
| + } |
| + scope := pageScopeOf(own) |
| + var out []string |
| + for h, up := range m { |
| + if strings.HasPrefix(h, "*") || up.route.Host != own.route.Host || pageScopeOf(up) != scope { |
| + continue |
| + } |
| + out = append(out, h) |
| + } |
| + slices.Sort(out) |
| + return out |
| +} |
| + |
| // 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. |
diff --git a/internal/edge/pageclear_test.go b/internal/edge/pageclear_test.go| new file mode 100644 |
| index 000000000..160df9c16 |
| --- /dev/null |
| +++ b/internal/edge/pageclear_test.go |
| @@ -0,0 +1,411 @@ |
| +package edge |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Clears reach the page index (edge page cache plan 1, Task 8): today's |
| +// purge channels, the Carlos-Purge response header and the control socket's |
| +// POST /purge, clear pages as well as LRU entries, and both take the |
| +// instance-wide target "all". A spawn's PurgeHost never clears a page. |
| + |
| +const ( |
| + pcAlias = "www.example.com" |
| + pcAlias2 = "blog.example.org" |
| + pcOther = "other.example.com" // another instance of the same app |
| +) |
| + |
| +// clearingApp answers a GET with a marked page of its path, and a POST with |
| +// the Carlos-Purge and Carlos-Purge-Host values the test put on the request |
| +// (X-Test-Purge, X-Test-Purge-Host). Inbound Carlos-Purge headers are |
| +// scrubbed by the edge, so the test names them under its own. |
| +func clearingApp(w http.ResponseWriter, r *http.Request) { |
| + if r.Method == http.MethodPost { |
| + if v := r.Header.Get("X-Test-Purge"); v != "" { |
| + w.Header().Set(PurgeHeader, v) |
| + } |
| + if v := r.Header.Get("X-Test-Purge-Host"); v != "" { |
| + w.Header().Set(PurgeHostHeader, v) |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| + return |
| + } |
| + pageOK(pcBody)(w, r) |
| +} |
| + |
| +// newClearScene is newPCScene over clearingApp with pcAlias and pcAlias2 |
| +// attached to pcHost, and pcOther, another instance of the same app (so a |
| +// Carlos-Purge-Host may name it) on the same backend, armed for pages too. |
| +func newClearScene(t *testing.T) *pcScene { |
| + t.Helper() |
| + s := newPCScene(t, clearingApp) |
| + upsertAlias(t, s.reg, pcAlias, pcHost) |
| + upsertAlias(t, s.reg, pcAlias2, pcHost) |
| + other := s.rt |
| + other.Host = pcOther |
| + if err := s.reg.Upsert(other); err != nil { |
| + t.Fatalf("upsert: %v", err) |
| + } |
| + s.publishFor(other) |
| + if err := s.e.Reload(); err != nil { |
| + t.Fatalf("reload: %v", err) |
| + } |
| + return s |
| +} |
| + |
| +// cacheOf is the Carlos-Cache of one GET of path on host. |
| +func (s *pcScene) cacheOf(host, path string) string { |
| + s.t.Helper() |
| + rec := s.do(http.MethodGet, "http://"+host+path) |
| + if rec.Code != http.StatusOK || rec.Body.String() != pcBody { |
| + s.t.Fatalf("GET %s%s = %d %q", host, path, rec.Code, rec.Body.String()) |
| + } |
| + return rec.Header().Get("Carlos-Cache") |
| +} |
| + |
| +// keep caches each path on host as a page, and proves the next GET hits. |
| +func (s *pcScene) keep(host string, paths ...string) { |
| + s.t.Helper() |
| + for _, p := range paths { |
| + s.cacheOf(host, p) |
| + if got := s.cacheOf(host, p); got != "hit" { |
| + s.t.Fatalf("fixture: %s%s is %q after a store, want hit", host, p, got) |
| + } |
| + } |
| +} |
| + |
| +// wantCleared fails unless every path on host now misses (it is stored |
| +// again by the GET, as any miss is). |
| +func (s *pcScene) wantCleared(why, host string, paths ...string) { |
| + s.t.Helper() |
| + for _, p := range paths { |
| + if got := s.cacheOf(host, p); got != "miss" { |
| + s.t.Fatalf("%s: %s%s is %q, want miss (the page survived the clear)", why, host, p, got) |
| + } |
| + } |
| +} |
| + |
| +// wantKept fails unless every path on host still hits. |
| +func (s *pcScene) wantKept(why, host string, paths ...string) { |
| + s.t.Helper() |
| + for _, p := range paths { |
| + if got := s.cacheOf(host, p); got != "hit" { |
| + s.t.Fatalf("%s: %s%s is %q, want hit (the clear reached it)", why, host, p, got) |
| + } |
| + } |
| +} |
| + |
| +// purge POSTs to host, and the app answers with Carlos-Purge: value (and |
| +// Carlos-Purge-Host: hosts, when given). |
| +func (s *pcScene) purge(host, value string, hosts ...string) { |
| + s.t.Helper() |
| + hdr := []string{"X-Test-Purge", value} |
| + if len(hosts) > 0 { |
| + hdr = append(hdr, "X-Test-Purge-Host", strings.Join(hosts, ", ")) |
| + } |
| + rec := s.do(http.MethodPost, "http://"+host+"/admin", hdr...) |
| + if rec.Code != http.StatusNoContent { |
| + s.t.Fatalf("POST %s/admin = %d", host, rec.Code) |
| + } |
| + if rec.Header().Get(PurgeHeader) != "" || rec.Header().Get(PurgeHostHeader) != "" { |
| + s.t.Fatal("a purge header reached the client") |
| + } |
| +} |
| + |
| +func TestPurgeHeaderClearsPage(t *testing.T) { |
| + paths := []string{"/p", "/p?x=1", "/q"} |
| + cases := []struct { |
| + name string |
| + value string |
| + cleared []string |
| + kept []string |
| + }{ |
| + {"path clears every query", "/p", []string{"/p", "/p?x=1"}, []string{"/q"}}, |
| + {"url clears one variant", "/p?x=1", []string{"/p?x=1"}, []string{"/p", "/q"}}, |
| + {"empty query is the bare url", "/p?", []string{"/p"}, []string{"/p?x=1", "/q"}}, |
| + {"star clears the host", "*", paths, nil}, |
| + {"star subsumes the rest", "/q, *", paths, nil}, |
| + {"a list", "/q, /p?x=1", []string{"/q", "/p?x=1"}, []string{"/p"}}, |
| + {"malformed clears nothing", "p, http://x/p", nil, paths}, |
| + {"over the count clears the host", strings.Repeat("/z, ", maxPurgeTargets) + "/z", paths, nil}, |
| + {"over the bytes clears the host", "/" + strings.Repeat("z", maxPurgeHeaderBytes), paths, nil}, |
| + } |
| + for _, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + s := newClearScene(t) |
| + s.keep(pcHost, paths...) |
| + s.keep(pcOther, "/p") |
| + s.purge(pcHost, tc.value) |
| + s.wantKept("another instance", pcOther, "/p") |
| + s.wantKept(tc.name, pcHost, tc.kept...) |
| + s.wantCleared(tc.name, pcHost, tc.cleared...) |
| + }) |
| + } |
| + |
| + // Carlos-Purge-Host sends the targets to the hosts it names, and pages |
| + // follow: here a sibling instance's page, not the serving host's. |
| + t.Run("purge host", func(t *testing.T) { |
| + s := newClearScene(t) |
| + s.keep(pcHost, "/p") |
| + s.keep(pcOther, "/p", "/q") |
| + s.purge(pcHost, "/p", pcOther) |
| + s.wantKept("the serving host, not named", pcHost, "/p") |
| + s.wantKept("an unnamed path", pcOther, "/q") |
| + s.wantCleared("the named host", pcOther, "/p") |
| + }) |
| +} |
| + |
| +// TestPurgeHeaderOnStoredResponseOrder: a marked GET whose own response |
| +// carries Carlos-Purge for its own URL is not stored, because the ticket its |
| +// recording took predates the clear the response applies. The next GET is a |
| +// miss, and is stored. |
| +func TestPurgeHeaderOnStoredResponseOrder(t *testing.T) { |
| + var n atomic.Int64 |
| + s := newPCScene(t, func(w http.ResponseWriter, r *http.Request) { |
| + if n.Add(1) == 1 { |
| + w.Header().Set(PurgeHeader, "/post") |
| + } |
| + pageOK(pcBody)(w, r) |
| + }) |
| + rec := s.get("/post") |
| + wantCache(t, rec, "miss") |
| + wantBody(t, rec, 200, pcBody) |
| + if got := s.pages(); got != 0 { |
| + t.Fatalf("%d pages stored from a response that cleared its own URL", got) |
| + } |
| + wantCache(t, s.get("/post"), "miss") |
| + wantCache(t, s.get("/post"), "hit") |
| +} |
| + |
| +// TestPurgeAllClearsAliases is Review Focus 5. Carlos-Purge: * on an alias |
| +// clears that host's pages and leaves the instance's other aliases alone; |
| +// all clears the primary and every alias, from any of them, and touches no |
| +// other instance. |
| +func TestPurgeAllClearsAliases(t *testing.T) { |
| + hosts := []string{pcHost, pcAlias, pcAlias2} |
| + |
| + t.Run("star on an alias", func(t *testing.T) { |
| + s := newClearScene(t) |
| + for _, h := range hosts { |
| + s.keep(h, "/p", "/q") |
| + } |
| + s.purge(pcAlias, "*") |
| + s.wantKept("another alias", pcAlias2, "/p", "/q") |
| + s.wantCleared("the alias asked", pcAlias, "/p", "/q") |
| + }) |
| + |
| + t.Run("path on an alias", func(t *testing.T) { |
| + s := newClearScene(t) |
| + for _, h := range hosts { |
| + s.keep(h, "/p", "/q") |
| + } |
| + s.purge(pcAlias, "/p") |
| + s.wantKept("another alias", pcAlias2, "/p", "/q") |
| + s.wantKept("an unnamed path", pcAlias, "/q") |
| + s.wantCleared("the alias asked", pcAlias, "/p") |
| + }) |
| + |
| + for _, from := range hosts { |
| + for _, value := range []string{"all", "/q, all, *"} { |
| + t.Run("all from "+from+" as "+strconv.Quote(value), func(t *testing.T) { |
| + s := newClearScene(t) |
| + for _, h := range hosts { |
| + s.keep(h, "/p", "/q?x=1") |
| + } |
| + s.keep(pcOther, "/p") |
| + s.purge(from, value) |
| + s.wantKept("another instance", pcOther, "/p") |
| + for _, h := range hosts { |
| + s.wantCleared("all", h, "/p", "/q?x=1") |
| + } |
| + }) |
| + } |
| + } |
| + |
| + // all with Carlos-Purge-Host clears every host of each named instance. |
| + t.Run("all on a named host", func(t *testing.T) { |
| + s := newClearScene(t) |
| + s.keep(pcHost, "/p") |
| + s.keep(pcOther, "/p") |
| + s.purge(pcHost, "all", pcOther) |
| + s.wantKept("the serving instance, not named", pcHost, "/p") |
| + s.wantCleared("the named instance", pcOther, "/p") |
| + }) |
| + |
| + // The LRU half: all purges every host of the instance, and only those. |
| + t.Run("lru", func(t *testing.T) { |
| + s := newPCScene(t, func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method == http.MethodPost { |
| + w.Header().Set(PurgeHeader, "all") |
| + w.WriteHeader(http.StatusNoContent) |
| + return |
| + } |
| + w.Header().Set("Content-Type", "text/html") |
| + w.Header().Set("Cache-Control", "public, max-age=600") |
| + io.WriteString(w, "plain "+r.Host+r.URL.Path) |
| + }) |
| + s.e.EnablePageCache(nil) |
| + upsertAlias(t, s.reg, pcAlias, pcHost) |
| + other := s.rt |
| + other.Host = pcOther |
| + if err := s.reg.Upsert(other); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, h := range []string{pcHost, pcAlias, pcOther} { |
| + s.do(http.MethodGet, "http://"+h+"/l") |
| + } |
| + if n := s.lruLen(); n != 3 { |
| + t.Fatalf("fixture: the LRU holds %d entries, want 3", n) |
| + } |
| + s.do(http.MethodPost, "http://"+pcAlias+"/admin") |
| + for _, h := range []string{pcHost, pcAlias} { |
| + if _, ok := s.e.cache.get(CacheKey{Host: h, Method: "GET", Path: "/l"}); ok { |
| + t.Fatalf("all left %s/l in the LRU", h) |
| + } |
| + } |
| + if _, ok := s.e.cache.get(CacheKey{Host: pcOther, Method: "GET", Path: "/l"}); !ok { |
| + t.Fatal("all purged another instance's LRU entry") |
| + } |
| + }) |
| +} |
| + |
| +// postSocketPurge POSTs body to the control socket's /purge and returns the |
| +// status. |
| +func postSocketPurge(t *testing.T, client *http.Client, body map[string]string) int { |
| + t.Helper() |
| + b, _ := json.Marshal(body) |
| + resp, err := client.Post("http://unix/purge", "application/json", bytes.NewReader(b)) |
| + if err != nil { |
| + t.Fatalf("purge POST: %v", err) |
| + } |
| + resp.Body.Close() |
| + return resp.StatusCode |
| +} |
| + |
| +func TestControlSocketClearsPageAndAll(t *testing.T) { |
| + hosts := []string{pcHost, pcAlias, pcAlias2} |
| + listen := func(t *testing.T, s *pcScene) *http.Client { |
| + sock := filepath.Join(shortPurgeSocketDir(t), "c.sock") |
| + ctl, err := ListenControl(sock, pcHost, s.e.cache, nil) |
| + if err != nil { |
| + t.Fatalf("ListenControl: %v", err) |
| + } |
| + t.Cleanup(func() { ctl.Close() }) |
| + return dialPurgeSocket(t, sock) |
| + } |
| + |
| + t.Run("url", func(t *testing.T) { |
| + s := newClearScene(t) |
| + c := listen(t, s) |
| + s.keep(pcHost, "/p", "/p?x=1", "/q") |
| + if code := postSocketPurge(t, c, map[string]string{"path": "/p", "query": "x=1"}); code != http.StatusOK { |
| + t.Fatalf("purge status = %d", code) |
| + } |
| + s.wantKept("other urls", pcHost, "/p", "/q") |
| + s.wantCleared("the url", pcHost, "/p?x=1") |
| + if code := postSocketPurge(t, c, map[string]string{"path": "/p"}); code != http.StatusOK { |
| + t.Fatalf("purge status = %d", code) |
| + } |
| + s.wantKept("other urls", pcHost, "/p?x=1", "/q") |
| + s.wantCleared("the bare url", pcHost, "/p") |
| + }) |
| + |
| + t.Run("star", func(t *testing.T) { |
| + s := newClearScene(t) |
| + c := listen(t, s) |
| + for _, h := range hosts { |
| + s.keep(h, "/p", "/q?x=1") |
| + } |
| + if code := postSocketPurge(t, c, map[string]string{"path": "*"}); code != http.StatusOK { |
| + t.Fatalf("purge status = %d", code) |
| + } |
| + s.wantKept("an alias", pcAlias, "/p", "/q?x=1") |
| + s.wantCleared("the host", pcHost, "/p", "/q?x=1") |
| + }) |
| + |
| + t.Run("all", func(t *testing.T) { |
| + s := newClearScene(t) |
| + c := listen(t, s) |
| + for _, h := range hosts { |
| + s.keep(h, "/p", "/q?x=1") |
| + } |
| + s.keep(pcOther, "/p") |
| + if code := postSocketPurge(t, c, map[string]string{"path": "all", "query": "x=1"}); code != http.StatusBadRequest { |
| + t.Fatalf("all with a query: status = %d, want 400", code) |
| + } |
| + s.wantKept("a refused body", pcAlias, "/p") |
| + if code := postSocketPurge(t, c, map[string]string{"path": "all"}); code != http.StatusOK { |
| + t.Fatalf("purge status = %d", code) |
| + } |
| + s.wantKept("another instance", pcOther, "/p") |
| + for _, h := range hosts { |
| + s.wantCleared("all", h, "/p", "/q?x=1") |
| + } |
| + }) |
| + |
| + // The LRU half of the socket's all: every host of the instance. |
| + t.Run("all lru", func(t *testing.T) { |
| + s := newPCScene(t, func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "text/html") |
| + w.Header().Set("Cache-Control", "public, max-age=600") |
| + io.WriteString(w, "plain") |
| + }) |
| + s.e.EnablePageCache(nil) |
| + upsertAlias(t, s.reg, pcAlias, pcHost) |
| + if err := s.e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + c := listen(t, s) |
| + for _, h := range []string{pcHost, pcAlias} { |
| + s.do(http.MethodGet, "http://"+h+"/l") |
| + } |
| + if n := s.lruLen(); n != 2 { |
| + t.Fatalf("fixture: the LRU holds %d entries, want 2", n) |
| + } |
| + if code := postSocketPurge(t, c, map[string]string{"path": "all"}); code != http.StatusOK { |
| + t.Fatalf("purge status = %d", code) |
| + } |
| + if n := s.lruLen(); n != 0 { |
| + t.Fatalf("all left %d LRU entries", n) |
| + } |
| + }) |
| +} |
| + |
| +// TestSpawnPurgeKeepsPages: a process start purges the host's LRU entries |
| +// (Cache.PurgeHost, as every activator start site does) and publishes its |
| +// inputs. Neither clears a page: a wake with the same inputs still hits. |
| +func TestSpawnPurgeKeepsPages(t *testing.T) { |
| + s := newPCScene(t, pageOK(pcBody), func(r *registry.Route) { r.Hibernate = true }) |
| + s.act.onWake = func(rt registry.Route) { |
| + s.e.cache.PurgeHost(rt.Host) |
| + s.publishFor(rt) |
| + } |
| + upsertAlias(t, s.reg, pcAlias, pcHost) |
| + if err := s.e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantCache(t, s.get("/p"), "miss") |
| + wantCache(t, s.do(http.MethodGet, "http://"+pcAlias+"/p"), "miss") |
| + before := s.pages() |
| + wantCache(t, s.get("/other"), "miss") // a wake |
| + s.e.cache.PurgeHost(pcHost) |
| + s.e.cache.PurgeHost(pcAlias) |
| + if got := s.pages(); got != before+1 { |
| + t.Fatalf("%d pages after a spawn's purge, want %d", got, before+1) |
| + } |
| + wantCache(t, s.get("/p"), "hit") |
| + wantCache(t, s.do(http.MethodGet, "http://"+pcAlias+"/p"), "hit") |
| +} |
diff --git a/internal/edge/purge.go b/internal/edge/purge.go| index 4e2f61466..cf9dd44f3 100644 |
| --- a/internal/edge/purge.go |
| +++ b/internal/edge/purge.go |
| @@ -4,6 +4,8 @@ import ( |
| "encoding/json" |
| "net" |
| "net/http" |
| + |
| + "github.com/carlosframework/platform/internal/pageindex" |
| ) |
| // ControlListener is an instance's local-only control channel: the socket |
| @@ -44,6 +46,14 @@ type PurgeListener = ControlListener |
| // names nothing a request could be stored under, so it is refused rather than |
| // guessed at: widening a malformed exact purge to the whole host is not a |
| // reading the caller asked for. |
| +// |
| +// {"path":"all"} is the one body that reaches past the listener's host |
| +// (edge page cache plan 1, Task 8): every host of the same instance, its |
| +// primary and every alias the edge routes to it, never another instance's. |
| +// It too is refused with a query. |
| +// |
| +// Every body clears pages as well (purgeBridge): the matching pages of the |
| +// listener's host, or for "all" every page of the instance. |
| type purgeRequest struct { |
| Path string `json:"path"` |
| Query string `json:"query"` |
| @@ -63,7 +73,9 @@ const purgeAllPath = "*" |
| // construction, and never taken from the request — purgeRequest carries |
| // only Path and Query, never a host — so no request body, however |
| // malicious or malformed, can make this listener purge any host other than |
| -// the one it was built for. That closes a confused-deputy purge: an |
| +// the one it was built for, or for {"path":"all"} the other hosts the edge's |
| +// own route table gives that host's instance (its aliases), found from host |
| +// alone. That closes a confused-deputy purge: an |
| // attacker (or a bug) cannot use one instance's control channel to reach |
| // into another host's cache entries THROUGH this listener. schedule.Mount |
| // takes host by the same discipline, for the same reason. |
| @@ -137,7 +149,16 @@ func ListenControl(socketPath, host string, cache *Cache, mount func(*http.Serve |
| http.Error(w, "bad request", http.StatusBadRequest) |
| return |
| } |
| - if req.Path == purgeAllPath { |
| + // The bridge to the edge's page index: nil when no edge armed |
| + // this cache, and then only the LRU is purged. |
| + bridge := cache.purgeBridgeOf() |
| + clearPages := func(c pageindex.Clear) { |
| + if bridge != nil { |
| + bridge.clearPages(host, c) |
| + } |
| + } |
| + switch req.Path { |
| + case purgeAllPath: |
| if req.Query != "" { |
| http.Error(w, "bad request: path \"*\" takes no query", http.StatusBadRequest) |
| return |
| @@ -145,10 +166,27 @@ func ListenControl(socketPath, host string, cache *Cache, mount func(*http.Serve |
| // host is still the one this listener was built for: "*" widens |
| // the purge to every path of that host, never to another host. |
| cache.PurgeHost(host) |
| - w.WriteHeader(http.StatusOK) |
| - return |
| + clearPages(pageindex.Clear{Targets: []pageindex.Target{{Kind: pageindex.TargetHost}}}) |
| + case purgeInstanceTarget: |
| + if req.Query != "" { |
| + http.Error(w, "bad request", http.StatusBadRequest) |
| + return |
| + } |
| + // Every host of host's own instance, found in the edge's live |
| + // route table by host, never by anything in the body. |
| + cache.PurgeHost(host) |
| + if bridge != nil { |
| + for _, h := range bridge.instanceHosts(host) { |
| + if h != host { |
| + cache.PurgeHost(h) |
| + } |
| + } |
| + } |
| + clearPages(pageindex.Clear{}) |
| + default: |
| + cache.PurgeURL(host, req.Path, req.Query) |
| + clearPages(pageindex.Clear{Targets: []pageindex.Target{{Kind: pageindex.TargetURL, Path: req.Path, RawQuery: req.Query}}}) |
| } |
| - cache.PurgeURL(host, req.Path, req.Query) |
| w.WriteHeader(http.StatusOK) |
| }) |
| } |
diff --git a/internal/edge/purge_header.go b/internal/edge/purge_header.go| index 9b590e2a0..101351ab7 100644 |
| --- a/internal/edge/purge_header.go |
| +++ b/internal/edge/purge_header.go |
| @@ -2,12 +2,14 @@ package edge |
| import ( |
| "fmt" |
| + "net" |
| "net/http" |
| "net/http/httputil" |
| "net/url" |
| "slices" |
| "strings" |
| + "github.com/carlosframework/platform/internal/pageindex" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -59,8 +61,21 @@ import ( |
| // TestPurgeHeaderListedInConnectionIsEatenBeforeTheHook. |
| // - It is never read from a REQUEST, and is scrubbed off every proxied |
| // request before the app sees it (scrubInboundPurgeHeader). |
| +// - It clears PAGES too (edge page cache plan 1, Task 8): every target |
| +// clears the page index's matching pages of each host it reaches, as it |
| +// purges that host's LRU entries. With no Carlos-Purge-Host, the host the |
| +// request was asked on is cleared as well as the serving route's, so a |
| +// write served on an alias clears that alias's pages. |
| +// - The bare target "all" reaches every host of the instance: the LRU |
| +// entries of its primary and every alias, and every page of the |
| +// instance. With Carlos-Purge-Host it applies to each named host's |
| +// instance. It subsumes every other target, "*" included. |
| const PurgeHeader = "Carlos-Purge" |
| +// purgeInstanceTarget is the Carlos-Purge target (and the control socket |
| +// path) that clears every host of the instance. |
| +const purgeInstanceTarget = "all" |
| + |
| // PurgeHostHeader lets one response redirect its whole Carlos-Purge |
| // declaration at one or more SIBLING routes of the same app and account — |
| // spec §6.4, widened from one host to a list by amadan carlos/platform#173. |
| @@ -300,7 +315,11 @@ func scrubInboundPurgeHeader(pr *httputil.ProxyRequest) { |
| // this hook needs no lock and cannot tear against a concurrent Reload. |
| func (e *Edge) purgeModifier(rt registry.Route) func(*http.Response) error { |
| return func(resp *http.Response) error { |
| - e.applyPurgeHeader(rt, resp.Header) |
| + asked := "" |
| + if resp.Request != nil { |
| + asked = resp.Request.Host |
| + } |
| + e.applyPurgeHeader(rt, asked, resp.Header) |
| return nil |
| } |
| } |
| @@ -314,7 +333,11 @@ func (e *Edge) purgeModifier(rt registry.Route) func(*http.Response) error { |
| // box with a cache does. Carlos-Purge-Host is stripped even when there is no |
| // Carlos-Purge beside it: a response that names a sibling host and asks for |
| // nothing is a no-op purge, not a header a client may see. |
| -func (e *Edge) applyPurgeHeader(rt registry.Route, h http.Header) { |
| +// |
| +// asked is the Host the request was sent to, port and all (resp.Request: every |
| +// tenant proxy's Rewrite sets Out.Host = In.Host). It widens the PAGE half of |
| +// a declaration with no Carlos-Purge-Host: see pageHostsFor. |
| +func (e *Edge) applyPurgeHeader(rt registry.Route, asked string, h http.Header) { |
| // joinHeader, never h.Get: Carlos-Purge is legitimately list-valued and |
| // may arrive on several lines (RFC 9110 §5.3 — one comma-joined line and |
| // several lines mean the same thing, and http.Header.Add produces the |
| @@ -337,7 +360,37 @@ func (e *Edge) applyPurgeHeader(rt registry.Route, h http.Header) { |
| if !ok { |
| return |
| } |
| - e.applyPurgeTargets(rt.Host, hosts, joined) |
| + pageHosts := hosts |
| + if len(declared) == 0 { |
| + pageHosts = e.pageHostsFor(rt, asked) |
| + } |
| + e.applyPurgeTargets(rt.Host, hosts, pageHosts, joined) |
| +} |
| + |
| +// pageHostsFor is the hosts whose pages a declaration with no |
| +// Carlos-Purge-Host clears: the serving route's own host, as for the LRU, |
| +// and the host the request was asked on when that is another host of the |
| +// same instance (an alias, or a name served through a wildcard alias). |
| +// |
| +// The LRU keeps today's single host. Pages differ because they are keyed by |
| +// the host asked for and live for up to a year, so a write served on an |
| +// alias that cleared only the primary would leave the alias's page stale for |
| +// that long. A host that routes elsewhere (a path-routed front host, whose |
| +// pages are never stored) is not added: the default never reaches beyond the |
| +// instance that answered. |
| +func (e *Edge) pageHostsFor(rt registry.Route, asked string) []string { |
| + host := asked |
| + if h, _, err := net.SplitHostPort(host); err == nil { |
| + host = h |
| + } |
| + if host == "" || host == rt.Host { |
| + return []string{rt.Host} |
| + } |
| + up, ok := lookupIn(e.current(), host) |
| + if !ok || up.route.Host != rt.Host || pageScopeOf(up) != pageScopeOf(upstream{route: rt}) { |
| + return []string{rt.Host} |
| + } |
| + return []string{rt.Host, host} |
| } |
| // resolvePurgeHosts decides which hosts this response's purge targets apply |
| @@ -594,8 +647,20 @@ func validPurgeOverrideHost(h string) bool { |
| } |
| // applyPurgeTargets parses one response's joined Carlos-Purge value once and |
| -// applies it to every host in hosts. from is the serving route's host, and |
| -// keys the log lines: it is the route whose response declared the purge. |
| +// applies it to every host in hosts: the LRU calls first, then the same |
| +// targets to the page index (clearPages) for every host in pageHosts. from is |
| +// the serving route's host, and keys the log lines: it is the route whose |
| +// response declared the purge. |
| +// |
| +// pageHosts is hosts, or with no Carlos-Purge-Host, hosts plus the alias the |
| +// request was asked on (pageHostsFor). The target "all" ignores it: for each |
| +// host in hosts it purges the LRU of every host of that host's instance and |
| +// clears the instance's every page. |
| +// |
| +// This runs in the response modifier, before the response is considered for |
| +// either cache. A page recording of this very response took its ticket before |
| +// the proxy ran, so a clear that matches it here fences it, and the response |
| +// that declared the clear is never stored. |
| // |
| // hosts has already been decided by resolvePurgeHosts — the serving route's |
| // own host, or the hosts a valid Carlos-Purge-Host listed. Everything below, |
| @@ -603,14 +668,20 @@ func validPurgeOverrideHost(h string) bool { |
| // construction: degrading to the SERVING host instead would be the worst of |
| // both, wiping a host nobody asked about while leaving the stale pages the app |
| // was trying to invalidate. |
| -func (e *Edge) applyPurgeTargets(from string, hosts []string, joined string) { |
| +func (e *Edge) applyPurgeTargets(from string, hosts, pageHosts []string, joined string) { |
| if len(hosts) == 0 { |
| return |
| } |
| + clearPages := func(targets []pageindex.Target) { |
| + for _, host := range pageHosts { |
| + e.clearPages(host, pageindex.Clear{Targets: targets}) |
| + } |
| + } |
| purgeHosts := func() { |
| for _, host := range hosts { |
| e.cache.PurgeHost(host) |
| } |
| + clearPages([]pageindex.Target{{Kind: pageindex.TargetHost}}) |
| } |
| if len(joined) > maxPurgeHeaderBytes { |
| e.logPurgeIssue("oversize", from, fmt.Sprintf( |
| @@ -632,6 +703,21 @@ func (e *Edge) applyPurgeTargets(from string, hosts []string, joined string) { |
| purgeHosts() |
| return |
| } |
| + // "all" anywhere subsumes every other target, "*" included, so it is |
| + // looked for first: before "*" returns, and before validPurgeTarget, which |
| + // would refuse a target that is not a path. |
| + if slices.Contains(targets, purgeInstanceTarget) { |
| + for _, host := range hosts { |
| + e.cache.PurgeHost(host) |
| + for _, h := range e.instanceHosts(host) { |
| + if h != host { |
| + e.cache.PurgeHost(h) |
| + } |
| + } |
| + e.clearPages(host, pageindex.Clear{}) |
| + } |
| + return |
| + } |
| // Parse every target before touching the cache, so the list is parsed once |
| // however many hosts it applies to, and so "*" anywhere subsumes the rest. |
| type key struct { |
| @@ -666,13 +752,24 @@ func (e *Edge) applyPurgeTargets(from string, hosts []string, joined string) { |
| } |
| } |
| } |
| + if len(keys) > 0 { |
| + pt := make([]pageindex.Target, 0, len(keys)) |
| + for _, k := range keys { |
| + if k.exact { |
| + pt = append(pt, pageindex.Target{Kind: pageindex.TargetURL, Path: k.path, RawQuery: k.rawQuery}) |
| + } else { |
| + pt = append(pt, pageindex.Target{Kind: pageindex.TargetPath, Path: k.path}) |
| + } |
| + } |
| + clearPages(pt) |
| + } |
| if rejected > 0 { |
| // One line per response, not one per target: a hostile app could |
| // otherwise turn every request into 64 log lines. The count is the |
| // signal; the first offender is the diagnostic. %q quotes any control |
| // bytes rather than emitting them into the journal. |
| e.logPurgeIssue("malformed", from, fmt.Sprintf( |
| - "%s: ignored %d malformed Carlos-Purge target(s), first %q — a target must be an absolute path or \"*\", and may never carry a host", |
| + "%s: ignored %d malformed Carlos-Purge target(s), first %q: a target must be an absolute path, \"*\" or \"all\", and may never carry a host", |
| from, rejected, truncateForLog(firstBad))) |
| } |
| } |