carlos / platform Public

edge: one routing snapshot with a remote path map (#186)

Reload now publishes one routeTable{hosts, remote}. remote holds the
prefix maps of path-routed hosts this box does not serve, built from
the route_paths rows every box derives (spec 5.2): forward hosts,
regional names and demo-reserved hosts or targets are skipped, and a
host whose rows name two claims is dropped and logged. current() keeps
its signature and returns the table's hosts; table() returns the whole
snapshot. The readers in certsettle, demo_api, replicaconsole and
holdsHost read the table; tests publish through storeHosts.

Reload reuses the route_paths rows it last read while the registry's
generation counter is unchanged, and rebuilds each host's paths and the
remote map from them on every Reload. At 10 hosts x 10,000 unserved
prefixes Reload is 18 ms (was ~124 ms); a Reload after a path write
reads the rows again (105 ms).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 29a5651c809353c72e99a7e6bc06e8daf9d50966 parent c31fe01
18 files changed, +501 −78
  • internal/edge/certsettle.go +3 −3
  • internal/edge/certsettle_test.go +2 −2
  • internal/edge/certsync_test.go +1 −1
  • internal/edge/certwarm_test.go +5 −5
  • internal/edge/demo_api.go +1 −1
  • internal/edge/demo_forward_test.go +1 −1
  • internal/edge/demo_response_test.go +2 −2
  • internal/edge/demo_traffic_test.go +2 −2
  • internal/edge/edge.go +17 −34
  • internal/edge/path_reload_bench_test.go +36 −20
  • internal/edge/pathremote.go +160 −0
  • internal/edge/pathremote_test.go +256 −0
  • internal/edge/replica_reach_test.go +1 −1
  • internal/edge/replicaconsole.go +1 −1
  • internal/edge/replicaproxy_test.go +2 −2
  • internal/edge/routetable_test.go +8 −0
  • internal/edge/steeringprobe_test.go +1 −1
  • internal/edge/wildcard_test.go +2 −2
diff --git a/internal/edge/certsettle.go b/internal/edge/certsettle.go
index 086363209..5066107eb 100644
--- a/internal/edge/certsettle.go
+++ b/internal/edge/certsettle.go
@@ -86,7 +86,7 @@ type nameAges struct {
now func() time.Time
mu sync.Mutex
- own *map[string]upstream
+ own *routeTable
homes *homeSnapshot
first map[string]time.Time
}
@@ -120,7 +120,7 @@ func (a *nameAges) wait(e *Edge, host string) time.Duration {
// rebuild re-reads both name sets when either has changed. Called with a.mu
// held.
func (a *nameAges) rebuild(e *Edge, baseline bool) {
- own := e.upstreams.Load()
+ own := e.table()
var snap *homeSnapshot
if hm := e.homes.Load(); hm != nil {
snap = hm.snapshot()
@@ -149,7 +149,7 @@ func (a *nameAges) rebuild(e *Edge, baseline bool) {
}
}
if own != nil {
- for h := range *own {
+ for h := range own.hosts {
note(h, baseline)
}
}
diff --git a/internal/edge/certsettle_test.go b/internal/edge/certsettle_test.go
index c6b98c900..dc997844c 100644
--- a/internal/edge/certsettle_test.go
+++ b/internal/edge/certsettle_test.go
@@ -61,7 +61,7 @@ func mint(e *Edge, host string) {
next[h] = u
}
next[host] = upstream{}
- e.upstreams.Store(&next)
+ e.storeHosts(next)
}
func TestHostPolicyHoldsANameItHasJustMinted(t *testing.T) {
@@ -173,7 +173,7 @@ func TestHostPolicyHoldsANameThatReturns(t *testing.T) {
t.Fatalf("baseline name: %v", err)
}
gone := map[string]upstream{"old.test": {}}
- e.upstreams.Store(&gone)
+ e.storeHosts(gone)
if err := pol(context.Background(), "old.test"); err != nil { // rebuild without mover
t.Fatalf("old.test: %v", err)
}
diff --git a/internal/edge/certsync_test.go b/internal/edge/certsync_test.go
index 075db4884..a015cbc3a 100644
--- a/internal/edge/certsync_test.go
+++ b/internal/edge/certsync_test.go
@@ -290,7 +290,7 @@ func testIssuerEdge(hosts ...string) *Edge {
for _, h := range hosts {
m[h] = upstream{}
}
- e.upstreams.Store(&m)
+ e.storeHosts(m)
return e
}
diff --git a/internal/edge/certwarm_test.go b/internal/edge/certwarm_test.go
index 80a4388e8..a2f6f2113 100644
--- a/internal/edge/certwarm_test.go
+++ b/internal/edge/certwarm_test.go
@@ -111,7 +111,7 @@ func TestWarmSetReadsPublicationNotTheRouteTable(t *testing.T) {
e, m, s := publishedEdge(t, `{"published.customer.test":{"role":"home","alias":true,"dns_pointing":true}}`)
putJSON(t, s, "control/edges/betty.json", `{"v":1,"box":"betty","eip":"2.2.2.2","hosts":{"elsewhere.customer.test":{"role":"home","alias":true,"dns_pointing":true}}}`)
refreshHomeMap(t, m)
- e.upstreams.Store(&map[string]upstream{
+ e.storeHosts(map[string]upstream{
"published.customer.test": {},
"fresh.customer.test": {alias: true}, // attached, not yet published
"firstroute.customer.test": {}, // a custom route, likewise
@@ -122,12 +122,12 @@ func TestWarmSetReadsPublicationNotTheRouteTable(t *testing.T) {
}
bare := &Edge{}
- bare.upstreams.Store(&map[string]upstream{"www.customer.test": {}})
+ bare.storeHosts(map[string]upstream{"www.customer.test": {}})
if got := bare.warmSet("oncarlos.test", nil); len(got) != 0 {
t.Fatalf("an edge with no home map warmed %v from its route table", got)
}
unlabelled := &Edge{}
- unlabelled.upstreams.Store(&map[string]upstream{"www.customer.test": {}})
+ unlabelled.storeHosts(map[string]upstream{"www.customer.test": {}})
um := newHomeMap(s, "")
refreshHomeMap(t, um)
unlabelled.homes.Store(um)
@@ -237,7 +237,7 @@ func (f *issuerWarmFixture) totalLookups() int {
func TestIssuerWarmDoesNotLookUpAnUnpublishedAlias(t *testing.T) {
const alias = "shop.example.com"
f := newIssuerWarmFixture(t, `{"app.acct.oncarlos.test":{"role":"home","platform":true}}`)
- f.e.upstreams.Store(&map[string]upstream{
+ f.e.storeHosts(map[string]upstream{
"app.acct.oncarlos.test": {},
alias: {alias: true},
})
@@ -267,7 +267,7 @@ func TestIssuerWarmDoesNotLookUpAnUnpublishedAlias(t *testing.T) {
func TestIssuerWarmWaitsForACustomRouteToPoint(t *testing.T) {
const own, remote = "shop.example.com", "store.example.net"
f := newIssuerWarmFixture(t, `{"`+own+`":{"role":"home","platform":false,"dns_pointing":false}}`)
- f.e.upstreams.Store(&map[string]upstream{own: {}})
+ f.e.storeHosts(map[string]upstream{own: {}})
f.publish(t, "betty", `{"`+remote+`":{"role":"home","platform":false,"dns_pointing":false}}`)
f.w.pass()
f.w.pass()
diff --git a/internal/edge/demo_api.go b/internal/edge/demo_api.go
index e5fca43d5..79cfa747d 100644
--- a/internal/edge/demo_api.go
+++ b/internal/edge/demo_api.go
@@ -156,7 +156,7 @@ func (e *Edge) serveDemoAPIAlias(w http.ResponseWriter, r *http.Request, host st
r.URL.Host = console
// Load exactly once: endpoint, identity, version and admission settings
// must all describe the same reload snapshot. Never use a wildcard/path.
- up, local := (*e.upstreams.Load())[console]
+ up, local := e.table().hosts[console]
if local {
if !demoAPIConsoleEligible(console, up) || up.demoAPIProxy == nil {
demoAPIUnavailable(dw)
diff --git a/internal/edge/demo_forward_test.go b/internal/edge/demo_forward_test.go
index edf934c88..b9fa3691c 100644
--- a/internal/edge/demo_forward_test.go
+++ b/internal/edge/demo_forward_test.go
@@ -31,7 +31,7 @@ func demoTestProxy(t *testing.T, target string) *httputil.ReverseProxy {
}
func demoSetProxy(e *Edge, rt registry.Route, handler http.Handler) {
m := map[string]upstream{rt.Host: {route: rt, proxy: handler}}
- e.upstreams.Store(&m)
+ e.storeHosts(m)
}
func demoDo(t *testing.T, base, host, method, path, encoding string) (*http.Response, []byte) {
t.Helper()
diff --git a/internal/edge/demo_response_test.go b/internal/edge/demo_response_test.go
index 658525d16..74ad26c25 100644
--- a/internal/edge/demo_response_test.go
+++ b/internal/edge/demo_response_test.go
@@ -138,11 +138,11 @@ func TestDemoPolicyEveryExit(t *testing.T) {
names, routes := e.demoNames.Load(), e.upstreams.Load()
t.Cleanup(func() { e.demoNames.Store(names); e.upstreams.Store(routes) })
e.demoNames.Store(&map[string]bool{})
- e.upstreams.Store(&map[string]upstream{})
+ e.storeHosts(map[string]upstream{})
published := false
ctx := &demoPublishContext{Context: context.Background(), publish: func() {
published = true
- e.upstreams.Store(&map[string]upstream{bad.Host: {route: bad, proxy: http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ e.storeHosts(map[string]upstream{bad.Host: {route: bad, proxy: http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
t.Error("post-lookup demo dispatched")
})}})
}}
diff --git a/internal/edge/demo_traffic_test.go b/internal/edge/demo_traffic_test.go
index db6140f2c..03c67b749 100644
--- a/internal/edge/demo_traffic_test.go
+++ b/internal/edge/demo_traffic_test.go
@@ -74,7 +74,7 @@ func demoTrafficFixture(t *testing.T, handler http.Handler) (*Edge, registry.Rou
e.gzipOn = false
m := map[string]upstream{host: {route: rt, proxy: handler}}
- e.upstreams.Store(&m)
+ e.storeHosts(m)
c := &demoTestCounter{caps: demo.TrafficCaps{Requests: 2000, BodyBytes: 200000000}}
e.SetDemoTraffic(c, func(registry.Route, time.Time) bool { return true })
return e, rt, c
@@ -588,7 +588,7 @@ func TestDemoTrafficCancelOnlyRevokedLifetime(t *testing.T) {
other.Socket = provision.NestedSocket(other.Host)
routes := e.current()
routes[other.Host] = upstream{route: other, proxy: routes[rt.Host].proxy}
- e.upstreams.Store(&routes)
+ e.storeHosts(routes)
var done sync.WaitGroup
run := func(host string) context.Context {
done.Add(1)
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index afca1bd0e..8835a1cd1 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -144,7 +144,9 @@ type Edge struct {
// hold is this Edge's local-upstream hold settings (localhold.go), set
// before the startup Reload and read by it.
hold localHold
- upstreams atomic.Pointer[map[string]upstream]
+ upstreams atomic.Pointer[routeTable] // the routing snapshot (pathremote.go)
+ // pathRows is the route_paths rows Reload reuses while unchanged.
+ pathRows pathRowCache
// act, when non-nil, is the hibernation activator: hibernate-flagged
// instance routes stop being always-on backends and become on-demand
// processes woken per request. Nil keeps the proxy-only behavior; with it
@@ -1431,36 +1433,14 @@ func (e *Edge) Reload() error {
// hostname inherits its map along with everything else it copies — an
// alias is meant to be indistinguishable from its primary, and a
// hostname that routed by prefix under one name but not the other would
- // be a trap.
- //
- // Targets are recorded as hostnames, not resolved here: every route is
- // already in m by this point, but resolving now would freeze a copy of
- // the target's entry, and the target's own row may still be rewritten by
- // the alias fold below.
- paths, err := e.reg.ListPaths()
+ // be a trap. Rows for hosts this box does not serve are kept for the
+ // remote map, built after every fold (attachPaths, pathremote.go). The
+ // read stays here, in Reload's body, for TestReloadAppliesLinkAuthFirst.
+ paths, err := e.pathRows.load(e.reg.PathsGeneration, func() ([]registry.RoutePath, error) { return e.reg.ListPaths() })
if err != nil {
return err
}
- for _, p := range paths {
- up, ok := m[p.Host]
- if !ok {
- // The hostname has no route on this box. The reconcile pass
- // should not have produced this row; nothing to attach it to.
- continue
- }
- // A forward host has no path map here (spec §4.4): every path of it
- // is the forward row's, and the fleet edge, which holds the app's
- // own paths, routes inside it. The gate's login POST relies on this
- // (§4.8): it is never re-resolved at the hub.
- if up.route.IsForward() {
- continue
- }
- if up.paths == nil {
- up.paths = make(map[string]string)
- }
- up.paths[p.Prefix] = p.Target
- m[p.Host] = up
- }
+ attachPaths(m, paths)
// Platform aliases (#338 follow-up, platformalias.go): an alias that
// shares one ready same-tenant route's socket resolves to that route's
// OWN entry, as an attached hostname does below, so a request to it
@@ -1533,10 +1513,12 @@ func (e *Edge) Reload() error {
}
}
e.foldRegional(m, routes, regionalRows)
+ regional := regionalNamesOf(m)
demoNames := demoRefusalNames(m, routes, aliases)
e.filterDemoRoutes(m, routes)
// Refusals hold through every fold above: last, so nothing re-adds them.
refusedHosts(m, verdict.Refused)
+ remote := buildRemotePaths(m, paths, forwardHostsOf(routes), regional, e.demoReserved)
// Fleet channel auth and the door's tenancy map, read before the routes
// loop (above), applied here as they always were. The link half of the
// set is the map SetLinkAuth already applied at the top, so for links
@@ -1592,7 +1574,7 @@ func (e *Edge) Reload() error {
// Before the publication: a request that misses a retiring copy's host
// in m must already find it retiring (R28).
e.noteRetiredCopies(prevMap, m)
- e.upstreams.Store(&m)
+ e.upstreams.Store(&routeTable{hosts: m, remote: remote})
if h := e.hooks; h != nil && h.afterPublish != nil {
_ = h.afterPublish(id)
}
@@ -1680,9 +1662,10 @@ func (e *Edge) logThrottled(key, msg string) {
}
}
+// current is the published snapshot's hosts; nil before the first Reload.
func (e *Edge) current() map[string]upstream {
- if p := e.upstreams.Load(); p != nil {
- return *p
+ if t := e.upstreams.Load(); t != nil {
+ return t.hosts
}
return nil
}
@@ -3385,11 +3368,11 @@ func writeHeldClosed(w http.ResponseWriter, deadline time.Duration) {
// hibernating route this edge holds streams for. An edge that has published
// no map yet (a bare Edge in a unit test) does not judge: true.
func (e *Edge) holdsHost(host string) bool {
- m := e.upstreams.Load()
- if m == nil {
+ t := e.table()
+ if t == nil {
return true
}
- u, ok := (*m)[host]
+ u, ok := t.hosts[host]
return ok && u.hibernating && u.route.Hibernate
}
diff --git a/internal/edge/path_reload_bench_test.go b/internal/edge/path_reload_bench_test.go
index f7303a021..c78884926 100644
--- a/internal/edge/path_reload_bench_test.go
+++ b/internal/edge/path_reload_bench_test.go
@@ -17,11 +17,10 @@ const (
pathReloadTargets = 10
)
-// pathReloadLocal is the placement the benchmark runs with. Today Reload
-// attaches a path row only to a front route this box serves, so the
-// workload must be local to survive the code under test; Task 5 flips this
-// to false (unserved hosts, whose rows land in the remote map).
-const pathReloadLocal = true
+// pathReloadLocal is the placement the benchmark runs with: false, so the
+// fronts and targets are hosts this box does not serve and every row lands
+// in the remote map (spec §5.2), the shape of every box but the home one.
+const pathReloadLocal = false
// pathReloadRegistry opens a registry holding hosts × pathReloadPrefixes
// route_paths rows, and, with local, the fronts' and targets' route rows.
@@ -60,22 +59,30 @@ func pathReloadRegistry(tb testing.TB, hosts int, local bool) *registry.Registry
return reg
}
-// pathReloadLive counts the path entries the published map holds.
+// pathReloadLive counts the path entries the published table holds, in the
+// served hosts' maps and in the remote map.
func pathReloadLive(e *Edge) int {
n := 0
- for _, up := range e.current() {
+ tb := e.table()
+ for _, up := range tb.hosts {
if up.alias {
continue // an alias carries its primary's map, not rows of its own
}
n += len(up.paths)
}
+ for _, rm := range tb.remote {
+ n += len(rm.prefixes)
+ }
return n
}
// BenchmarkReloadPaths is the cost budget's edge half (spec §6): one Reload
-// over a registry holding 1, 5 and 10 hosts × 10,000 path rows. After the
-// timing it checks the live map holds every row, so a workload the code
-// under test dropped cannot pass as cheap.
+// over a registry holding 1, 5 and 10 hosts × 10,000 path rows, with the
+// route_paths generation unchanged since the last Reload (the steady state:
+// the rows are reused). The cold sub-benchmark reads them again on every
+// Reload, the cost of the first Reload after a path write. After the timing
+// each checks the live table holds every row, so a workload the code under
+// test dropped cannot pass as cheap.
func BenchmarkReloadPaths(b *testing.B) {
for _, hosts := range []int{1, 5, 10} {
reg := pathReloadRegistry(b, hosts, pathReloadLocal)
@@ -83,16 +90,25 @@ func BenchmarkReloadPaths(b *testing.B) {
if err != nil {
b.Fatal(err)
}
- b.Run(fmt.Sprintf("hosts=%d", hosts), func(b *testing.B) {
- for i := 0; i < b.N; i++ {
- if err := e.Reload(); err != nil {
- b.Fatal(err)
- }
- }
- b.StopTimer()
- if got, want := pathReloadLive(e), hosts*pathReloadPrefixes; got != want {
- b.Fatalf("live map holds %d path entries, want %d", got, want)
+ for _, cold := range []bool{false, true} {
+ name := fmt.Sprintf("hosts=%d", hosts)
+ if cold {
+ name += "/cold"
}
- })
+ b.Run(name, func(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ if cold {
+ e.pathRows = pathRowCache{}
+ }
+ if err := e.Reload(); err != nil {
+ b.Fatal(err)
+ }
+ }
+ b.StopTimer()
+ if got, want := pathReloadLive(e), hosts*pathReloadPrefixes; got != want {
+ b.Fatalf("live table holds %d path entries, want %d", got, want)
+ }
+ })
+ }
}
}
diff --git a/internal/edge/pathremote.go b/internal/edge/pathremote.go
new file mode 100644
index 000000000..10d0aed44
--- /dev/null
+++ b/internal/edge/pathremote.go
@@ -0,0 +1,160 @@
+package edge
+
+// Path routes across boxes (#186, spec §5.2): the routing snapshot Reload
+// publishes, and the remote path map in it.
+//
+// Every box derives route_paths rows for every path-routed host, served here
+// or not (domains, Task 3). Rows whose host this box serves fold into that
+// host's own prefix map, as they always have. Rows whose host it does not
+// serve become the remote map: prefix -> target for a claim's own host, so
+// this box can make the selection the host's home box would make. Both
+// halves are published as one value, so a reader never pairs one Reload's
+// hosts with another's remote map.
+
+import (
+ "log"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// remotePathMap is one unserved host's prefix map.
+type remotePathMap struct {
+ prefixes map[string]string // prefix -> target host
+ account, app string // the claim's, from the rows
+}
+
+// routeTable is the one atomically published routing snapshot.
+type routeTable struct {
+ hosts map[string]upstream
+ remote map[string]remotePathMap
+}
+
+// table is the whole published snapshot; nil before the first Reload.
+func (e *Edge) table() *routeTable {
+ return e.upstreams.Load()
+}
+
+// pathRowCache is the route_paths rows Reload last read and the generation
+// it read before them (registry.PathsGeneration). Only Reload touches it,
+// under reloadMu.
+//
+// Reading 100,000 rows is most of a Reload at the cost budget's scale (spec
+// §6), and the rows change far less often than routes do. While the
+// generation is unchanged Reload reuses the rows; everything it makes from
+// them (each host's paths, the remote map) is rebuilt on every Reload,
+// because those also depend on the routes, aliases, regional rows and demo
+// settings the same Reload reads.
+type pathRowCache struct {
+ gen int64
+ rows []registry.RoutePath
+ ok bool // gen and rows are a pair this cache may reuse
+ // reads counts the reads load made: the test seam that shows a reuse.
+ reads int
+}
+
+// load answers the route_paths rows, from the cache while the generation
+// equals the one read with them, else from read. The generation is read
+// before the rows: a write between the two leaves newer rows under an older
+// generation, which the next load reads again; the other order could keep
+// older rows under a newer generation for good. A generation that cannot be
+// read (a registry no read-write open has migrated) is never reused.
+func (c *pathRowCache) load(generation func() (int64, error), read func() ([]registry.RoutePath, error)) ([]registry.RoutePath, error) {
+ gen, genErr := generation()
+ if genErr == nil && c.ok && gen == c.gen {
+ return c.rows, nil
+ }
+ c.reads++
+ rows, err := read()
+ if err != nil {
+ c.ok = false
+ return nil, err
+ }
+ c.gen, c.rows, c.ok = gen, rows, genErr == nil
+ return rows, nil
+}
+
+// attachPaths folds rows into the prefix maps of the hosts m already holds.
+// Targets are recorded as hostnames, not resolved: every route is in m by
+// now, but resolving would freeze a copy of the target's entry, and the
+// target's own row may still be rewritten by the alias fold. A target this
+// box does not serve stays in the map, so the host's own box can send that
+// prefix on (spec §5.3, case 2). A row whose host is not in m is not
+// attached: it is a host another box serves, and goes to the remote map
+// (buildRemotePaths), built after every fold.
+//
+// A forward host has no path map here (spec §4.4): every path of it is the
+// forward row's, and the fleet edge, which holds the app's own paths, routes
+// inside it. The gate's login POST relies on this (§4.8): it is never
+// re-resolved at the hub.
+//
+// Each host's map is new on every call: filterDemoRoutes deletes from it,
+// and rows may be a cache another Reload reuses.
+func attachPaths(m map[string]upstream, rows []registry.RoutePath) {
+ for _, p := range rows {
+ up, ok := m[p.Host]
+ if !ok || up.route.IsForward() {
+ continue
+ }
+ if up.paths == nil {
+ up.paths = make(map[string]string)
+ }
+ up.paths[p.Prefix] = p.Target
+ m[p.Host] = up
+ }
+}
+
+// forwardHostsOf is the hosts of the forward rows in routes, ready or not.
+func forwardHostsOf(routes []registry.Route) map[string]bool {
+ out := map[string]bool{}
+ for _, rt := range routes {
+ if rt.IsForward() {
+ out[rt.Host] = true
+ }
+ }
+ return out
+}
+
+// regionalNamesOf is the names the regional fold put in m, serve or deny.
+func regionalNamesOf(m map[string]upstream) map[string]bool {
+ out := map[string]bool{}
+ for host, up := range m {
+ if up.regional != regionalNone {
+ out[host] = true
+ }
+ }
+ return out
+}
+
+// buildRemotePaths is the remote map (spec §5.2): from rows, the prefix
+// maps of the hosts m does not hold, with the same filters as the local
+// fold. A row is skipped when its host is in m (it folded locally), is a
+// forward host, is a regional name on this box (Review Focus 3: no
+// cross-box selection for it), or when its host or target is demo-reserved
+// (filterDemoRoutes' rules). Only a claim's own host is keyed: the rows are
+// keyed by it, and aliases and catch-alls have none.
+//
+// One host's rows come from one claim. A host whose rows name two owners is
+// dropped, and logged, rather than routed for either.
+func buildRemotePaths(m map[string]upstream, rows []registry.RoutePath, forwardHosts, regional map[string]bool, demoReserved func(string) bool) map[string]remotePathMap {
+ out := map[string]remotePathMap{}
+ split := map[string]bool{}
+ for _, p := range rows {
+ if _, served := m[p.Host]; served || forwardHosts[p.Host] || regional[p.Host] || split[p.Host] ||
+ demoReserved(p.Host) || demoReserved(p.Target) {
+ continue
+ }
+ rm, ok := out[p.Host]
+ if !ok {
+ rm = remotePathMap{prefixes: map[string]string{}, account: p.Account, app: p.App}
+ out[p.Host] = rm
+ } else if rm.account != p.Account || rm.app != p.App {
+ split[p.Host] = true
+ delete(out, p.Host)
+ log.Printf("edge: paths on %s are not routed from this box: its rows name two claims (%s/%s and %s/%s)",
+ p.Host, rm.account, rm.app, p.Account, p.App)
+ continue
+ }
+ rm.prefixes[p.Prefix] = p.Target
+ }
+ return out
+}
diff --git a/internal/edge/pathremote_test.go b/internal/edge/pathremote_test.go
new file mode 100644
index 000000000..18556cd34
--- /dev/null
+++ b/internal/edge/pathremote_test.go
@@ -0,0 +1,256 @@
+package edge
+
+import (
+ "maps"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// remotePathRow writes one route_paths row for a claim of account/app.
+func remotePathRow(t *testing.T, reg *registry.Registry, host, prefix, target, account, app string) {
+ t.Helper()
+ if err := reg.UpsertPath(registry.RoutePath{Host: host, Prefix: prefix, Target: target, Account: account, App: app}); err != nil {
+ t.Fatalf("upsert path %s/%s -> %s: %v", host, prefix, target, err)
+ }
+}
+
+// remoteEdge is an Edge over reg, its first Reload done by New.
+func remoteEdge(t *testing.T, reg *registry.Registry) *Edge {
+ t.Helper()
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ return e
+}
+
+// readyRoute writes a ready instance route on an address nothing listens on:
+// Reload builds its proxy and never dials it.
+func readyRoute(t *testing.T, reg *registry.Registry, host, account, app string) {
+ t.Helper()
+ if err := reg.Upsert(registry.Route{Host: host, Account: account, App: app, Kind: "instance", Status: "ready", Addr: "127.0.0.1:1"}); err != nil {
+ t.Fatalf("upsert route %s: %v", host, err)
+ }
+}
+
+// TestRemotePathsBuiltForUnservedHosts: rows whose host this box does not
+// serve land in the snapshot's remote map with the claim's account and app;
+// rows whose host it serves fold into that host's own paths, as today, and
+// never into the remote map.
+func TestRemotePathsBuiltForUnservedHosts(t *testing.T) {
+ reg := openReg(t)
+ readyRoute(t, reg, "local.example", "acct", "front")
+ remotePathRow(t, reg, "local.example", "a", "far.example", "acct", "front")
+ remotePathRow(t, reg, "hub.example", "paulca", "t1.example", "acct", "hub")
+ remotePathRow(t, reg, "hub.example", "bob", "t2.example", "acct", "hub")
+ e := remoteEdge(t, reg)
+
+ tb := e.table()
+ if tb == nil {
+ t.Fatal("no routing table published")
+ }
+ got, ok := tb.remote["hub.example"]
+ if !ok {
+ t.Fatalf("remote map has no entry for hub.example: %v", tb.remote)
+ }
+ if want := map[string]string{"paulca": "t1.example", "bob": "t2.example"}; !maps.Equal(got.prefixes, want) {
+ t.Errorf("hub.example prefixes = %v, want %v", got.prefixes, want)
+ }
+ if got.account != "acct" || got.app != "hub" {
+ t.Errorf("hub.example claim = %s/%s, want acct/hub", got.account, got.app)
+ }
+ if _, ok := tb.remote["local.example"]; ok {
+ t.Error("a host this box serves has a remote map")
+ }
+ // A row whose target is not on this box stays in the host's own map.
+ if up := tb.hosts["local.example"]; up.paths["a"] != "far.example" {
+ t.Errorf("local.example paths = %v, want a -> far.example", up.paths)
+ }
+ if got := e.current(); !maps.EqualFunc(got, tb.hosts, func(a, b upstream) bool { return a.route.Host == b.route.Host }) {
+ t.Error("current() is not the published table's hosts")
+ }
+}
+
+// TestRemotePathsDropDisagreeingClaim: one host's rows come from one claim,
+// so rows that name two owners are not a map this box can trust. The host is
+// dropped, and said so.
+func TestRemotePathsDropDisagreeingClaim(t *testing.T) {
+ logs := captureLog(t)
+ rows := []registry.RoutePath{
+ {Host: "hub.example", Prefix: "a", Target: "t1.example", Account: "acct", App: "hub"},
+ {Host: "hub.example", Prefix: "b", Target: "t2.example", Account: "other", App: "hub"},
+ {Host: "ok.example", Prefix: "a", Target: "t1.example", Account: "acct", App: "ok"},
+ }
+ remote := buildRemotePaths(map[string]upstream{}, rows, nil, nil, func(string) bool { return false })
+ if _, ok := remote["hub.example"]; ok {
+ t.Error("a host whose rows disagree on the claim has a remote map")
+ }
+ if _, ok := remote["ok.example"]; !ok {
+ t.Error("an agreeing host lost its remote map")
+ }
+ if !strings.Contains(logs.String(), "hub.example") {
+ t.Errorf("no log names the dropped host; log:\n%s", logs.String())
+ }
+}
+
+// TestRemotePathsSkipRegionalName is Review Focus 3: a path-routed host that
+// is also a regional name on this box gets no remote map, through Reload
+// (the regional entry holds the key) and through the builder alone (a
+// regional name some later fold took out of the map).
+func TestRemotePathsSkipRegionalName(t *testing.T) {
+ reg := openReg(t)
+ remotePathRow(t, reg, "hub.example", "paulca", "t1.example", "acct", "hub")
+ if err := reg.ReplaceRegionalSet("hub.example", []registry.RegionalDomain{{Host: "hub.example", Account: "acct", App: "hub"}}); err != nil {
+ t.Fatal(err)
+ }
+ e := remoteEdge(t, reg)
+ if _, ok := e.table().remote["hub.example"]; ok {
+ t.Error("a regional name has a remote map")
+ }
+
+ rows := []registry.RoutePath{{Host: "hub.example", Prefix: "paulca", Target: "t1.example", Account: "acct", App: "hub"}}
+ remote := buildRemotePaths(map[string]upstream{}, rows, nil, map[string]bool{"hub.example": true}, func(string) bool { return false })
+ if _, ok := remote["hub.example"]; ok {
+ t.Error("buildRemotePaths built a map for a regional name")
+ }
+}
+
+// TestRemotePathsSkipForwardHost: a forward host has no path map here (spec
+// §4.4): the fleet edge holds the app's own paths. That holds when this box
+// does not serve the forward row either.
+func TestRemotePathsSkipForwardHost(t *testing.T) {
+ reg := openReg(t)
+ if err := reg.PutForward(forwardRow("shop.example.com", "home", "acct")); err != nil {
+ t.Fatal(err)
+ }
+ remotePathRow(t, reg, "shop.example.com", "shop", "other.example.com", "acct", "shop")
+ e := remoteEdge(t, reg)
+ tb := e.table()
+ if _, served := tb.hosts["shop.example.com"]; served {
+ t.Fatal("fixture: this box serves the forward row, so the test would not reach the forward rule")
+ }
+ if _, ok := tb.remote["shop.example.com"]; ok {
+ t.Error("a forward host has a remote map")
+ }
+}
+
+// TestRemotePathsSkipDemoReserved: a demo-reserved host has no remote map,
+// and a row naming a demo-reserved target is dropped while the host's other
+// prefixes stay (filterDemoRoutes' rules for the local map).
+func TestRemotePathsSkipDemoReserved(t *testing.T) {
+ reg := openReg(t)
+ remotePathRow(t, reg, "x.demo.example.com", "a", "t1.example", "acct", "hub")
+ remotePathRow(t, reg, "hub.example", "a", "y.demo.example.com", "acct", "hub")
+ remotePathRow(t, reg, "hub.example", "b", "t2.example", "acct", "hub")
+ e := remoteEdge(t, reg)
+ e.demo = demo.Config{Domain: "demo.example.com"}
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ tb := e.table()
+ if _, ok := tb.remote["x.demo.example.com"]; ok {
+ t.Error("a demo-reserved host has a remote map")
+ }
+ if got, want := tb.remote["hub.example"].prefixes, map[string]string{"b": "t2.example"}; !maps.Equal(got, want) {
+ t.Errorf("hub.example prefixes = %v, want %v (the demo-reserved target dropped)", got, want)
+ }
+}
+
+// TestReloadPublishesOneSnapshot: the hosts and the remote map are one
+// atomically published value. A reader looping over e.table() while Reload
+// runs again and again on an unchanged registry never sees a table without
+// the remote map or without the local host's paths.
+func TestReloadPublishesOneSnapshot(t *testing.T) {
+ reg := openReg(t)
+ readyRoute(t, reg, "local.example", "acct", "front")
+ remotePathRow(t, reg, "local.example", "a", "far.example", "acct", "front")
+ remotePathRow(t, reg, "hub.example", "paulca", "t1.example", "acct", "hub")
+ e := remoteEdge(t, reg)
+
+ stop, done := make(chan struct{}), make(chan struct{})
+ var seen, torn atomic.Int64
+ go func() {
+ defer close(done)
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+ tb := e.table()
+ seen.Add(1)
+ if tb == nil || tb.remote["hub.example"].prefixes["paulca"] != "t1.example" || tb.hosts["local.example"].paths["a"] != "far.example" {
+ torn.Add(1)
+ }
+ }
+ }()
+ for range 50 {
+ if err := e.Reload(); err != nil {
+ close(stop)
+ <-done
+ t.Fatal(err)
+ }
+ }
+ close(stop)
+ <-done
+ if n := torn.Load(); n != 0 {
+ t.Errorf("%d of %d observed tables lacked the remote map or the local paths", n, seen.Load())
+ }
+}
+
+// TestReloadReusesPathsWhileGenerationUnchanged is the cost budget's Reload
+// half (spec §6): while route_paths' generation is unchanged, Reload reuses
+// the rows it last read instead of reading them again, and still rebuilds
+// what it makes from them against the routes it read now. A path write
+// makes it read again.
+func TestReloadReusesPathsWhileGenerationUnchanged(t *testing.T) {
+ reg := openReg(t)
+ remotePathRow(t, reg, "hub.example", "paulca", "t1.example", "acct", "hub")
+ e := remoteEdge(t, reg)
+ reads := e.pathRows.reads
+ if reads != 1 {
+ t.Fatalf("New's Reload read the path rows %d times, want 1", reads)
+ }
+
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if got := e.pathRows.reads; got != reads {
+ t.Fatalf("a Reload with no path write read the rows again (%d reads, want %d)", got, reads)
+ }
+ if e.table().remote["hub.example"].prefixes["paulca"] != "t1.example" {
+ t.Fatal("the reused rows built no remote map")
+ }
+
+ // A route change alone: the rows are reused, and the host now served
+ // here takes them as its own paths, out of the remote map.
+ readyRoute(t, reg, "hub.example", "acct", "hub")
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if got := e.pathRows.reads; got != reads {
+ t.Fatalf("a route write made Reload read the path rows (%d reads, want %d)", got, reads)
+ }
+ tb := e.table()
+ if _, ok := tb.remote["hub.example"]; ok {
+ t.Error("a host served here kept its remote map")
+ }
+ if tb.hosts["hub.example"].paths["paulca"] != "t1.example" {
+ t.Errorf("hub.example paths = %v, want paulca -> t1.example", tb.hosts["hub.example"].paths)
+ }
+
+ remotePathRow(t, reg, "hub.example", "bob", "t2.example", "acct", "hub")
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if got := e.pathRows.reads; got != reads+1 {
+ t.Fatalf("a path write: %d reads, want %d", got, reads+1)
+ }
+ if e.table().hosts["hub.example"].paths["bob"] != "t2.example" {
+ t.Error("the new row is not in the published map")
+ }
+}
diff --git a/internal/edge/replica_reach_test.go b/internal/edge/replica_reach_test.go
index 18f4dab7f..3ba335c03 100644
--- a/internal/edge/replica_reach_test.go
+++ b/internal/edge/replica_reach_test.go
@@ -251,7 +251,7 @@ func TestReplicaDeadCopyRetriedOnSurvivor(t *testing.T) {
}
}
ups := map[string]upstream{rt.Host: {route: rt, proxy: proxy, viaTunnel: true}}
- e.upstreams.Store(&ups)
+ e.storeHosts(ups)
records := &memRecorder{}
e.EnableRequestRecords(records)
var body io.Reader
diff --git a/internal/edge/replicaconsole.go b/internal/edge/replicaconsole.go
index 508310010..f69d88821 100644
--- a/internal/edge/replicaconsole.go
+++ b/internal/edge/replicaconsole.go
@@ -99,7 +99,7 @@ func (e *Edge) serveReplicaConsole(w http.ResponseWriter, r *http.Request) {
return
}
var console http.Handler
- for host, up := range *e.upstreams.Load() {
+ for host, up := range e.table().hosts {
rt := up.route
if host != rt.Host || up.alias || up.regional != 0 || up.viaTunnel || rt.Account != "" || rt.App != "console" || rt.Unit != "console.service" || rt.ActivatorOwned() {
continue
diff --git a/internal/edge/replicaproxy_test.go b/internal/edge/replicaproxy_test.go
index 93f42ae18..1c183ed14 100644
--- a/internal/edge/replicaproxy_test.go
+++ b/internal/edge/replicaproxy_test.go
@@ -201,7 +201,7 @@ func replicaUpgradeAdmission(h *TunnelHub, rt registry.Route) upgradeAdmission {
ten := tenancy{Arm: ArmForward, Account: rt.Account, App: rt.App, Fleet: "pi"}
e := &Edge{}
ups := map[string]upstream{rt.Host: {route: rt, tenancy: ten}}
- e.upstreams.Store(&ups)
+ e.storeHosts(ups)
h.edge = e
return upgradeAdmission{Host: rt.Host, Path: "/socket", Tenancy: ten}
}
@@ -315,7 +315,7 @@ func TestReplicaClientResponseMeteredOnce(t *testing.T) {
e := edgeWithBackend(t, http.NotFoundHandler())
// Fixture-only installation; Reload and FleetArmVerdict belong to Task 3.
ups := map[string]upstream{rt.Host: {route: rt, proxy: replicaProxy(rt.Host, "pi", p, h), viaTunnel: true}}
- e.upstreams.Store(&ups)
+ e.storeHosts(ups)
meter := NewUsageMeter()
e.EnableUsage(meter)
records := &memRecorder{}
diff --git a/internal/edge/routetable_test.go b/internal/edge/routetable_test.go
new file mode 100644
index 000000000..323558a74
--- /dev/null
+++ b/internal/edge/routetable_test.go
@@ -0,0 +1,8 @@
+package edge
+
+// storeHosts publishes m as the routing table with no remote map: a test's
+// stand-in for Reload. Here, in a _test.go file, because Reload is the only
+// publisher of the table in the package's code (TestReloadIsTheOnlyPublisher).
+func (e *Edge) storeHosts(m map[string]upstream) {
+ e.upstreams.Store(&routeTable{hosts: m})
+}
diff --git a/internal/edge/steeringprobe_test.go b/internal/edge/steeringprobe_test.go
index dfb590154..0b7edec6a 100644
--- a/internal/edge/steeringprobe_test.go
+++ b/internal/edge/steeringprobe_test.go
@@ -155,7 +155,7 @@ func TestSteeringArmsTheAppsDomainWildcardParent(t *testing.T) {
t.Setenv("CARLOS_DNSIMPLE_TOKEN", "tok")
e := &Edge{}
- e.upstreams.Store(&map[string]upstream{})
+ e.storeHosts(map[string]upstream{})
w := newWildcardFromEnv(e, cache)
if w == nil {
t.Fatal("want a manager")
diff --git a/internal/edge/wildcard_test.go b/internal/edge/wildcard_test.go
index 091e45a62..af6009e41 100644
--- a/internal/edge/wildcard_test.go
+++ b/internal/edge/wildcard_test.go
@@ -370,7 +370,7 @@ func TestWrappedGetCertificateFallsThrough(t *testing.T) {
func TestNewWildcardFromEnv(t *testing.T) {
e := &Edge{}
- e.upstreams.Store(&map[string]upstream{})
+ e.storeHosts(map[string]upstream{})
cache := autocert.DirCache(t.TempDir())
t.Setenv("CARLOS_WILDCARD_DOMAINS", "")
@@ -425,7 +425,7 @@ func TestOnReloadHookFires(t *testing.T) {
// bound, pinned below.
func TestCurrentHostsPlatformOnly(t *testing.T) {
e := &Edge{}
- e.upstreams.Store(&map[string]upstream{
+ e.storeHosts(map[string]upstream{
"app.acct.oncarlos.com": {route: registry.Route{Host: "app.acct.oncarlos.com", Platform: true}},
"review.bcd.oncarlos.com": {route: registry.Route{Host: "review.bcd.oncarlos.com", Provisioned: true}},
"story.example.com": {route: registry.Route{Host: "story.example.com", Provisioned: true}},