carlos / platform Public

edge: purges act for the authorized instance; all reaches wildcard hosts

Review fixes for Task 8. Every page clear and every "all" expansion now
names the instance it acts for instead of resolving a hostname afresh:
the serving route for its own host and aliases, the validated route for
a Carlos-Purge-Host entry (the serving route when the entry was admitted
by path routing), all judged against one route-table snapshot. The
control socket pins its host's route when the listener is built. A
response in flight while its hostname moves to another instance can no
longer clear that instance's pages or its aliases' LRU entries.

"all" now also purges LRU entries cached under names served through the
instance's wildcard alias: each cached host that resolves to the same
instance, with exact routes winning as they do for serving.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f6ada51968ed15f3f76395f5526b592e73cd7d0b parent 6ca0bab
5 files changed, +432 −71
  • internal/edge/cache.go +27 −7
  • internal/edge/pagecache.go +53 −29
  • internal/edge/pageclear_test.go +240 −0
  • internal/edge/purge.go +35 −4
  • internal/edge/purge_header.go +77 −31

Intent

Human

<task-notification> <task-id>ac22e61fd10fe7542</task-id> <tool-use-id>toolu_01Xz96Bv9A1FSwhUNDrBpzfd</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/ac22e61fd10fe7542.output</output-file> <status>completed</status> <summary>Agent "Implement Task 8: clears reach the index" 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 (one commit; please check the one deviation below). Commit: 6ca0baba edge: Carlos-Purge and the control socket clear pages; add the all target Tests: all 5 new tests in `internal/edge/pageclear_test.go` fail on the base code except `TestSpawnPurgeKeepsPages`, which guards current behaviour. All 5 pass after the change, including under `-race`. `-run 'Purge|Page|Alias|Cache'` in edge and the activator purge/inputs/control tests pass. The windows and darwin builds pass, and 9 of 10 code mutations were caught (the one that survived changes nothing). Concerns: 1. **Deviation:** the brief's wiring alone would not meet Review Focus 5's "`Carlos-Purge: *` on an alias clears that alias's pages". An alias's purge targets the primary, so the alias's pages would stay stale for up to a year. I added `pageHostsFor`: with no Carlos-Purge-Host, pages are also cleared on the host the request was sent to, if it is the same instance. The LRU is unchanged. Revert it if you want pages to stay exactly in step with the LRU. 2. A `*` or path purge sent on an alias still reaches only the primary's LRU entries, as before this task. 3. `instanceHosts` cannot list names served through a wildcard alias. `all` still clears their pages, but their LRU entries wait out the TTL. 4. No existing test needed changing: none used `all` as a target. 5. `copy-review/result.json` and `copy-review/strings.json` were already changed before I started; I didn't touch or stage them. 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-8-report.md</result> <usage><subagent_tokens>169119</subagent_tokens><tool_uses>57</tool_uses><duration_ms>1146297</duration_ms></usage> </task-notification>

Human

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

Attributed to this commit: 23.4 g CO₂e (3,057,165 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 b492b3bed..29c07bb8e 100644
--- a/internal/edge/cache.go
+++ b/internal/edge/cache.go
@@ -104,14 +104,23 @@ type Cache struct {
// 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.
+//
+// Every call names the instance it acts for (owner), never a host to be
+// resolved afresh: a hostname can move to another instance while a purge
+// is on its way, and a purge must never clear another instance's cache.
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
+ // ownerOf is the route the live table gives host as its own primary:
+ // false when host is not routed, or is routed as another route's alias.
+ ownerOf(host string) (registry.Route, bool)
+ // clearPages applies c to owner's pages, with host as the one host of
+ // a per-host clear (c with targets). An edge with no page cache clears
+ // nothing.
+ clearPages(owner registry.Route, host string, c pageindex.Clear)
+ // instanceHosts is every host the live table routes to owner's
+ // instance (its primary and every alias) together with every host in
+ // cached that the table serves as that instance (a name served through
+ // a wildcard alias).
+ instanceHosts(owner registry.Route, cached []string) []string
}
type purgeBridgeRef struct{ b purgeBridge }
@@ -125,6 +134,17 @@ func (c *Cache) setBridge(b purgeBridge) {
c.bridge.Store(&purgeBridgeRef{b})
}
+// cachedHosts lists every host the LRU holds an entry for.
+func (c *Cache) cachedHosts() []string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ out := make([]string, 0, len(c.byHost))
+ for h := range c.byHost {
+ out = append(out, h)
+ }
+ return out
+}
+
// purgeBridgeOf is the installed bridge, or nil.
func (c *Cache) purgeBridgeOf() purgeBridge {
if r := c.bridge.Load(); r != nil {
diff --git a/internal/edge/pagecache.go b/internal/edge/pagecache.go
index 1cf6e83ef..e4c39e425 100644
--- a/internal/edge/pagecache.go
+++ b/internal/edge/pagecache.go
@@ -44,24 +44,37 @@ 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.
+// routeScope is the page scope of rt's instance.
+func routeScope(rt registry.Route) pageindex.Scope { return pageScopeOf(upstream{route: rt}) }
+
+// sameInstance reports whether a and b are one instance: the same primary
+// host, app and account, which is to say the same page scope.
+func sameInstance(a, b registry.Route) bool { return routeScope(a) == routeScope(b) }
+
+// ownerOf is host's own route in the live table (purgeBridge): false when
+// host is not routed, or its entry is another route's (an alias).
+func (e *Edge) ownerOf(host string) (registry.Route, bool) {
+ up, ok := e.current()[host]
+ if !ok || up.route.Host != host {
+ return registry.Route{}, false
+ }
+ return up.route, true
+}
+
+// clearPages applies c to the pages of owner's instance (purgeBridge). The
+// scope is owner's own, never one looked up by host, so a hostname that has
+// moved to another instance since owner was authorized cannot carry the
+// clear there. 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.
//
// 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) {
+func (e *Edge) clearPages(owner registry.Route, host string, c pageindex.Clear) {
x := e.pages.Load()
- if x == nil {
- return
- }
- up, ok := lookupIn(e.current(), host)
- if !ok {
+ if x == nil || owner.Host == "" {
return
}
switch {
@@ -72,29 +85,40 @@ func (e *Edge) clearPages(host string, c pageindex.Clear) {
default:
c.Hosts = []string{host}
}
- x.Clear(pageScopeOf(up), c)
+ x.Clear(routeScope(owner), 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 == "" {
+// instanceHosts is instanceHostsIn over one snapshot of the live table
+// (purgeBridge).
+func (e *Edge) instanceHosts(owner registry.Route, cached []string) []string {
+ return instanceHostsIn(e.current(), owner, cached)
+}
+
+// instanceHostsIn is every host m serves as owner's instance, sorted: each
+// key whose entry is that instance (the primary and every alias), and each
+// host in cached that m resolves (lookupIn) to that instance. The second
+// half finds the names served through a wildcard alias, which the LRU keys
+// by the name asked for and m cannot list; lookupIn lets an exact key win
+// over the wildcard, so a name another instance's route takes is never
+// among them. A wildcard key itself is a routing pattern, not a name
+// anything is cached under, and is left out. Nil when owner has no host.
+func instanceHostsIn(m map[string]upstream, owner registry.Route, cached []string) []string {
+ if owner.Host == "" {
return nil
}
- scope := pageScopeOf(own)
- var out []string
+ set := map[string]bool{}
for h, up := range m {
- if strings.HasPrefix(h, "*") || up.route.Host != own.route.Host || pageScopeOf(up) != scope {
- continue
+ if !strings.HasPrefix(h, "*") && sameInstance(up.route, owner) {
+ set[h] = true
}
+ }
+ for _, h := range cached {
+ if up, ok := lookupIn(m, h); ok && sameInstance(up.route, owner) {
+ set[h] = true
+ }
+ }
+ out := make([]string, 0, len(set))
+ for h := range set {
out = append(out, h)
}
slices.Sort(out)
diff --git a/internal/edge/pageclear_test.go b/internal/edge/pageclear_test.go
index 160df9c16..bc8c0213f 100644
--- a/internal/edge/pageclear_test.go
+++ b/internal/edge/pageclear_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"io"
"net/http"
+ "net/http/httptest"
"path/filepath"
"strconv"
"strings"
@@ -409,3 +410,242 @@ func TestSpawnPurgeKeepsPages(t *testing.T) {
wantCache(t, s.get("/p"), "hit")
wantCache(t, s.do(http.MethodGet, "http://"+pcAlias+"/p"), "hit")
}
+
+// ---- review fixes: the authorized instance, and wildcard-served hosts ------
+
+// TestPurgeCannotReachAReplacementInstance: A's response is in flight while
+// A's hostname, and so its alias, is reassigned to B (another app). The
+// purge A's response declares, on its own host or on the alias, clears only
+// A's pages and never B's pages or B's alias LRU entries.
+func TestPurgeCannotReachAReplacementInstance(t *testing.T) {
+ for _, tc := range []struct{ name, from, value string }{
+ {"all from the primary", pcHost, "all"},
+ {"all from the alias", pcAlias, "all"},
+ {"star from the primary", pcHost, "*"},
+ {"star from the alias", pcAlias, "*"},
+ {"path from the alias", pcAlias, "/p"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ entered, release := make(chan struct{}), make(chan struct{})
+ s := newPCScene(t, func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodPost:
+ entered <- struct{}{}
+ <-release
+ w.Header().Set(PurgeHeader, tc.value)
+ w.WriteHeader(http.StatusNoContent)
+ case r.URL.Path == "/l":
+ w.Header().Set("Content-Type", "text/html")
+ w.Header().Set("Cache-Control", "public, max-age=600")
+ io.WriteString(w, "plain")
+ default:
+ pageOK(pcBody)(w, r)
+ }
+ })
+ upsertAlias(t, s.reg, pcAlias, pcHost)
+ if err := s.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ s.keep(pcHost, "/p")
+ s.keep(pcAlias, "/p")
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ s.e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "http://"+tc.from+"/admin", nil))
+ }()
+ <-entered
+ // The hostname now belongs to B, app shop, and so does the alias.
+ s.decl.loadFor("abc", "shop", pcBuild, "/assets/")
+ s.setRoute(func(r *registry.Route) { r.App = "shop" })
+ s.publish()
+ s.keep(pcHost, "/p")
+ s.keep(pcAlias, "/p")
+ s.do(http.MethodGet, "http://"+pcAlias+"/l") // B is opted in: no LRU
+ close(release)
+ <-done
+
+ s.wantKept("B's page", pcHost, "/p")
+ s.wantKept("B's alias page", pcAlias, "/p")
+ })
+ }
+
+ // The LRU half: B is not opted in, and A's all must not expand to B's
+ // alias. (A's own host is purged as "*" always purged it.)
+ t.Run("lru", func(t *testing.T) {
+ entered, release := make(chan struct{}), make(chan struct{})
+ s := newPCScene(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodPost {
+ entered <- struct{}{}
+ <-release
+ 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")
+ })
+ s.e.EnablePageCache(nil)
+ upsertAlias(t, s.reg, pcAlias, pcHost)
+ if err := s.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ s.e.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "http://"+pcHost+"/admin", nil))
+ }()
+ <-entered
+ s.setRoute(func(r *registry.Route) { r.App = "shop" })
+ s.do(http.MethodGet, "http://"+pcAlias+"/l")
+ close(release)
+ <-done
+ if _, ok := s.e.cache.get(CacheKey{Host: pcAlias, Method: "GET", Path: "/l"}); !ok {
+ t.Fatal("A's all purged B's alias from the LRU")
+ }
+ })
+}
+
+// TestControlSocketCannotReachAReplacementInstance: the listener built for
+// A's host keeps A as its instance. After the hostname moves to B, its
+// purges clear only A's pages and never expand to B's hosts.
+func TestControlSocketCannotReachAReplacementInstance(t *testing.T) {
+ for _, path := range []string{"all", "*", "/p"} {
+ t.Run(path, func(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody))
+ upsertAlias(t, s.reg, pcAlias, pcHost)
+ if err := s.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ 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() })
+ c := dialPurgeSocket(t, sock)
+ s.keep(pcHost, "/p")
+
+ s.decl.loadFor("abc", "shop", pcBuild, "/assets/")
+ s.setRoute(func(r *registry.Route) { r.App = "shop" })
+ s.publish()
+ s.keep(pcHost, "/p")
+ s.keep(pcAlias, "/p")
+ if code := postSocketPurge(t, c, map[string]string{"path": path}); code != http.StatusOK {
+ t.Fatalf("purge status = %d", code)
+ }
+ s.wantKept("B's page", pcHost, "/p")
+ s.wantKept("B's alias page", pcAlias, "/p")
+ })
+ }
+}
+
+// TestPurgeAllClearsWildcardServedHosts: all purges the LRU entries cached
+// under names served through the instance's wildcard alias, on both
+// channels, and not a name an exact route of another instance takes.
+func TestPurgeAllClearsWildcardServedHosts(t *testing.T) {
+ const (
+ wild = "*.example.org"
+ shop = "shop.example.org" // served through wild
+ exact = "exact.example.org" // its own route: another instance
+ )
+ for _, channel := range []string{"header", "socket"} {
+ t.Run(channel, 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")
+ })
+ s.e.EnablePageCache(nil)
+ upsertAlias(t, s.reg, wild, pcHost)
+ other := s.rt
+ other.Host, other.App = exact, "other"
+ 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, shop, exact} {
+ s.do(http.MethodGet, "http://"+h+"/l")
+ }
+ if n := s.lruLen(); n != 3 {
+ t.Fatalf("fixture: the LRU holds %d entries, want 3", n)
+ }
+ if channel == "header" {
+ s.do(http.MethodPost, "http://"+pcHost+"/admin")
+ } else {
+ sock := filepath.Join(shortPurgeSocketDir(t), "c.sock")
+ ctl, err := ListenControl(sock, pcHost, s.e.cache, nil)
+ if err != nil {
+ t.Fatalf("ListenControl: %v", err)
+ }
+ defer ctl.Close()
+ if code := postSocketPurge(t, dialPurgeSocket(t, sock), map[string]string{"path": "all"}); code != http.StatusOK {
+ t.Fatalf("purge status = %d", code)
+ }
+ }
+ for _, h := range []string{pcHost, shop} {
+ 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: exact, Method: "GET", Path: "/l"}); !ok {
+ t.Fatal("all purged an exact route of another instance")
+ }
+ })
+ }
+}
+
+// TestPurgeAllOnAPathRoutedHostStaysInTheServingApp: a Carlos-Purge-Host
+// admitted only because it path-routes to the serving route acts for the
+// serving route. all purges that host as "*" would, and never expands to
+// the other app's instance (its alias here).
+func TestPurgeAllOnAPathRoutedHostStaysInTheServingApp(t *testing.T) {
+ const (
+ front = "front.example.com"
+ frontAlias = "www.front.example.com"
+ )
+ s := newPCScene(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodPost {
+ w.Header().Set(PurgeHostHeader, front)
+ 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")
+ })
+ s.e.EnablePageCache(nil)
+ 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)
+ }
+ upsertAlias(t, s.reg, frontAlias, front)
+ if err := s.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ for _, h := range []string{pcHost, front, frontAlias} {
+ 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://"+pcHost+"/admin")
+ if _, ok := s.e.cache.get(CacheKey{Host: front, Method: "GET", Path: "/l"}); ok {
+ t.Fatal("all did not purge the named host")
+ }
+ if _, ok := s.e.cache.get(CacheKey{Host: frontAlias, Method: "GET", Path: "/l"}); !ok {
+ t.Fatal("all expanded into another app's instance")
+ }
+}
diff --git a/internal/edge/purge.go b/internal/edge/purge.go
index cf9dd44f3..9efa190fe 100644
--- a/internal/edge/purge.go
+++ b/internal/edge/purge.go
@@ -4,8 +4,10 @@ import (
"encoding/json"
"net"
"net/http"
+ "sync"
"github.com/carlosframework/platform/internal/pageindex"
+ "github.com/carlosframework/platform/internal/registry"
)
// ControlListener is an instance's local-only control channel: the socket
@@ -143,6 +145,28 @@ func ListenControl(socketPath, host string, cache *Cache, mount func(*http.Serve
mux := http.NewServeMux()
if cache != nil {
+ // owner is the instance this listener purges for: host's own route
+ // in the edge's table, pinned when the listener is built, so a purge
+ // arriving after host has moved to another instance clears only this
+ // one's pages and never expands to the newcomer's hosts. A host the
+ // table does not hold yet (a first start can outrun the edge's
+ // reload) is pinned at the first purge instead.
+ var (
+ ownerMu sync.Mutex
+ owner registry.Route
+ pinned bool
+ )
+ ownerFor := func(b purgeBridge) (registry.Route, bool) {
+ ownerMu.Lock()
+ defer ownerMu.Unlock()
+ if !pinned {
+ owner, pinned = b.ownerOf(host)
+ }
+ return owner, pinned
+ }
+ if b := cache.purgeBridgeOf(); b != nil {
+ ownerFor(b)
+ }
mux.HandleFunc("POST /purge", func(w http.ResponseWriter, r *http.Request) {
var req purgeRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -152,9 +176,16 @@ func ListenControl(socketPath, host string, cache *Cache, mount func(*http.Serve
// 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()
+ var own registry.Route
+ if bridge != nil {
+ var ok bool
+ if own, ok = ownerFor(bridge); !ok {
+ bridge = nil // no instance to act for: the LRU only
+ }
+ }
clearPages := func(c pageindex.Clear) {
if bridge != nil {
- bridge.clearPages(host, c)
+ bridge.clearPages(own, host, c)
}
}
switch req.Path {
@@ -172,11 +203,11 @@ func ListenControl(socketPath, host string, cache *Cache, mount func(*http.Serve
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.
+ // Every host of the pinned instance, found in the edge's live
+ // route table, never by anything in the body.
cache.PurgeHost(host)
if bridge != nil {
- for _, h := range bridge.instanceHosts(host) {
+ for _, h := range bridge.instanceHosts(own, cache.cachedHosts()) {
if h != host {
cache.PurgeHost(h)
}
diff --git a/internal/edge/purge_header.go b/internal/edge/purge_header.go
index 101351ab7..1289964ee 100644
--- a/internal/edge/purge_header.go
+++ b/internal/edge/purge_header.go
@@ -356,15 +356,30 @@ func (e *Edge) applyPurgeHeader(rt registry.Route, asked string, h http.Header)
if joined == "" || e.cache == nil {
return
}
- hosts, ok := e.resolvePurgeHosts(rt, declared)
+ // ONE snapshot of the route table for the whole declaration: the hosts
+ // it reaches, the instance each acts for, and the hosts "all" expands to
+ // are all judged against the same table.
+ cur := e.current()
+ owned, ok := e.resolvePurgeOwnersIn(cur, rt, declared)
if !ok {
return
}
- pageHosts := hosts
+ pages := owned
if len(declared) == 0 {
- pageHosts = e.pageHostsFor(rt, asked)
+ pages = pageHostsFor(cur, rt, asked)
}
- e.applyPurgeTargets(rt.Host, hosts, pageHosts, joined)
+ e.applyPurgeTargets(cur, rt.Host, owned, pages, joined)
+}
+
+// purgeHost is one host a purge declaration reaches, with the instance it
+// acts for there: owner is the route whose cache the purge may clear. The
+// serving route rt is the owner of its own host and its aliases. A host a
+// valid Carlos-Purge-Host names is owned by the route it was validated
+// against, in the same snapshot, or by rt when it was admitted only because
+// it path-routes to rt (the pages rt produces under it are rt's).
+type purgeHost struct {
+ host string
+ owner registry.Route
}
// pageHostsFor is the hosts whose pages a declaration with no
@@ -378,19 +393,23 @@ func (e *Edge) applyPurgeHeader(rt registry.Route, asked string, h http.Header)
// 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 {
+//
+// Both are owned by rt: the clear is of rt's own pages, whatever m says the
+// hostname is now.
+func pageHostsFor(m map[string]upstream, rt registry.Route, asked string) []purgeHost {
+ own := []purgeHost{{rt.Host, rt}}
host := asked
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
if host == "" || host == rt.Host {
- return []string{rt.Host}
+ return own
}
- up, ok := lookupIn(e.current(), host)
- if !ok || up.route.Host != rt.Host || pageScopeOf(up) != pageScopeOf(upstream{route: rt}) {
- return []string{rt.Host}
+ up, ok := lookupIn(m, host)
+ if !ok || !sameInstance(up.route, rt) {
+ return own
}
- return []string{rt.Host, host}
+ return append(own, purgeHost{host, rt})
}
// resolvePurgeHosts decides which hosts this response's purge targets apply
@@ -402,8 +421,22 @@ func (e *Edge) pageHostsFor(rt registry.Route, asked string) []string {
//
// declared is every Carlos-Purge-Host LINE, already removed from the response.
func (e *Edge) resolvePurgeHosts(rt registry.Route, declared []string) ([]string, bool) {
+ owned, ok := e.resolvePurgeOwnersIn(e.current(), rt, declared)
+ if !ok {
+ return nil, false
+ }
+ hosts := make([]string, len(owned))
+ for i, o := range owned {
+ hosts[i] = o.host
+ }
+ return hosts, true
+}
+
+// resolvePurgeOwnersIn is resolvePurgeHosts against the snapshot cur, with
+// the instance each accepted host acts for (purgeHost).
+func (e *Edge) resolvePurgeOwnersIn(cur map[string]upstream, rt registry.Route, declared []string) ([]purgeHost, bool) {
if len(declared) == 0 {
- return []string{rt.Host}, true
+ return []purgeHost{{rt.Host, rt}}, true
}
// The byte cap first, so that nothing below it — the split, the dedupe,
// the log lines — does work proportional to a header the app made huge.
@@ -452,11 +485,11 @@ func (e *Edge) resolvePurgeHosts(rt registry.Route, declared []string) ([]string
return nil, false
}
}
- // e.current(), not a captured map: the route table is live, and a sibling
- // added after this proxy was built must still validate. ONE snapshot for
- // the whole list, so every entry is judged against the same table.
- cur := e.current()
- hosts := make([]string, 0, len(vals))
+ // cur is e.current(), not a captured map: the route table is live, and a
+ // sibling added after this proxy was built must still validate. ONE
+ // snapshot for the whole list, so every entry is judged against the same
+ // table.
+ hosts := make([]purgeHost, 0, len(vals))
var unserved []string
servingChecked := false
for _, host := range vals {
@@ -464,7 +497,7 @@ func (e *Edge) resolvePurgeHosts(rt registry.Route, declared []string) ([]string
// Naming your own host is trivially in-tenancy and needs no lookup,
// so an app can emit the header unconditionally from shared code
// even on the route whose pages it is already allowed to purge.
- hosts = append(hosts, host)
+ hosts = append(hosts, purgeHost{host, rt})
continue
}
// lookupIn, not cur[host]: a host served through a wildcard key
@@ -508,7 +541,13 @@ func (e *Edge) resolvePurgeHosts(rt registry.Route, declared []string) ([]string
rt.Host, rt.App, rt.Account, truncateForLog(host), up.route.App, up.route.Account, truncateForLog(host)))
return nil, false
}
- hosts = append(hosts, host)
+ owner := up.route
+ if owner.App != rt.App {
+ // Admitted by the path-routing exception: the pages rt serves
+ // under host are rt's, and nothing of the other app's is.
+ owner = rt
+ }
+ hosts = append(hosts, purgeHost{host, owner})
}
if len(unserved) > 0 {
// One line per response, not one per entry, and only after the whole
@@ -668,18 +707,18 @@ 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, pageHosts []string, joined string) {
+func (e *Edge) applyPurgeTargets(cur map[string]upstream, from string, hosts, pageHosts []purgeHost, joined string) {
if len(hosts) == 0 {
return
}
clearPages := func(targets []pageindex.Target) {
- for _, host := range pageHosts {
- e.clearPages(host, pageindex.Clear{Targets: targets})
+ for _, p := range pageHosts {
+ e.clearPages(p.owner, p.host, pageindex.Clear{Targets: targets})
}
}
purgeHosts := func() {
- for _, host := range hosts {
- e.cache.PurgeHost(host)
+ for _, p := range hosts {
+ e.cache.PurgeHost(p.host)
}
clearPages([]pageindex.Target{{Kind: pageindex.TargetHost}})
}
@@ -706,15 +745,22 @@ func (e *Edge) applyPurgeTargets(from string, hosts, pageHosts []string, joined
// "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.
+ //
+ // Each host is purged as "*" would purge it, and the expansion is to the
+ // hosts cur serves as that host's OWNER (purgeHost), never to whatever
+ // instance holds the hostname now: a response still in flight when its
+ // hostname moved to another instance cannot reach that instance's
+ // aliases or pages.
if slices.Contains(targets, purgeInstanceTarget) {
- for _, host := range hosts {
- e.cache.PurgeHost(host)
- for _, h := range e.instanceHosts(host) {
- if h != host {
+ cached := e.cache.cachedHosts()
+ for _, p := range hosts {
+ e.cache.PurgeHost(p.host)
+ for _, h := range instanceHostsIn(cur, p.owner, cached) {
+ if h != p.host {
e.cache.PurgeHost(h)
}
}
- e.clearPages(host, pageindex.Clear{})
+ e.clearPages(p.owner, p.host, pageindex.Clear{})
}
return
}
@@ -743,12 +789,12 @@ func (e *Edge) applyPurgeTargets(from string, hosts, pageHosts []string, joined
}
keys = append(keys, key{path, rawQuery, exact})
}
- for _, host := range hosts {
+ for _, p := range hosts {
for _, k := range keys {
if k.exact {
- e.cache.PurgeURL(host, k.path, k.rawQuery)
+ e.cache.PurgeURL(p.host, k.path, k.rawQuery)
} else {
- e.cache.PurgePath(host, k.path)
+ e.cache.PurgePath(p.host, k.path)
}
}
}