carlos / platform Public

edge: far asset catch and fill (asset cache plan 3 Task 6)

An edge that does not hold a route now answers the declared asset paths
of a host another box homes from its own store, on both forwarding paths
(the exact-remote precedence branch and the lookup-miss branch), never
for a verified hop, a door caller or an upgrade.

A miss leads or joins a flight. The leader sends the allow-listed GET to
the home over the backhaul, as a signed hop carrying X-Carlos-Asset-Fill,
under a backhaul slot taken with the initiating client's fair-share key
(429 when shed, 503 + Retry-After: 2 when saturated). A response with a
valid acknowledgement is metered once here under the published owner and
stored when its X-Carlos-Asset-Expires is non-zero and this edge's own
admission, size, trailer veto and reservation pass, at the home's expiry
unchanged. A response without one is served as it came, answered bypass,
neither metered nor stored. Waiters get the entry or make their own plain
backhaul. Hits pass the owner's account throttle with a synthetic
instance route (drift D8). The acknowledgement, expiry and fill headers
and trailers never reach a client, and a client-sent X-Carlos-Asset-Fill
is stripped from every non-hop request (ack and expiry from every
request).

fillFromApp's machinery becomes runAssetFill with a pluggable judge and
dispatch, shared by the local, home and far fills; fakeHomeEdge records
the method, the assertion and the headers it saw.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 799fc1278ad4ab6152650c6131fe7ee866a6a334 parent 3882284
4 files changed, +1,240 −35
  • internal/edge/asset_far_test.go +879 −0
  • internal/edge/assetcatch.go +320 −31
  • internal/edge/edge.go +26 −3
  • internal/edge/homemap_test.go +15 −1
diff --git a/internal/edge/asset_far_test.go b/internal/edge/asset_far_test.go
new file mode 100644
index 000000000..8aaec5fff
--- /dev/null
+++ b/internal/edge/asset_far_test.go
@@ -0,0 +1,879 @@
+package edge
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/assetcache"
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/ratelimit"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The far catch and fill (edge asset cache design §5.1 to §5.5, §8; plan 3
+// Task 6).
+//
+// Not acceptance: one far Edge with a real plan 2 store and a real home map,
+// backhauling over real TLS (fakeHomeEdge) to a fake home that answers a fill
+// with or without an acknowledgement, or, where a test needs the home's own
+// entry, to a real home Edge with a fake policy (Task 5's laScene). Task 9 is
+// the two-edge acceptance gate.
+
+// farHome is the fake home: it runs app, and when ack is on and the request
+// carries an assertion it answers with X-Carlos-Asset-Expires (expires()) and
+// an acknowledgement signed with the deployment's mesh key. It checks nothing
+// itself: what the far edge sent is asserted from fakeHomeEdge's record.
+type farHome struct {
+ key []byte
+ mu sync.Mutex
+ ack bool
+ expires func() int64
+ app http.HandlerFunc
+}
+
+func (h *farHome) set(f func(h *farHome)) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ f(h)
+}
+
+func (h *farHome) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ h.mu.Lock()
+ ack, expires, app := h.ack, h.expires, h.app
+ h.mu.Unlock()
+ if a := r.Header.Get(assetFillHeader); a != "" && ack {
+ exp := expires()
+ w.Header().Set(assetExpiresHeader, strconv.FormatInt(exp, 10))
+ w.Header().Set(assetAckHeader, signAssetAck(h.key, a, exp))
+ }
+ app(w, r)
+}
+
+type farScene struct {
+ e *Edge
+ m *homeMap
+ meshKey []byte
+ home *farHome // nil when the home is a real Edge
+ rec *homeEdgeRecord
+ eip string
+ store *assetcache.Store
+ meter *UsageMeter
+ offset atomic.Int64 // the far clock minus real time, in nanoseconds
+ dialPort atomic.Value // string: where the backhaul transport dials
+}
+
+// newFarScene is a far edge (box annie, serving locals) and a fake home
+// (box betty) that homes laHost and publishes its asset block, acknowledging
+// fills with an expiry an hour ahead.
+func newFarScene(t *testing.T, app http.HandlerFunc, locals ...string) *farScene {
+ t.Helper()
+ var home *farHome
+ s := newFarEdge(t, func(key []byte, _ *homeMap) http.Handler {
+ home = &farHome{key: key, ack: true, app: app,
+ expires: func() int64 { return time.Now().Add(time.Hour).Unix() }}
+ return home
+ }, locals...)
+ s.home = home
+ return s
+}
+
+// newFarEdge builds the far edge and a home answering with the handler mk
+// returns, given the mesh key and the far edge's home map (whose store a real
+// home shares for its keys).
+func newFarEdge(t *testing.T, mk func(key []byte, m *homeMap) http.Handler, locals ...string) *farScene {
+ t.Helper()
+ e, m, key := hopEdge(t, "annie", locals...)
+ rec, eip := fakeHomeEdge(t, mk(key, m))
+ s := &farScene{e: e, m: m, meshKey: key, rec: rec, eip: eip, store: openLAStore(t), meter: NewUsageMeter()}
+ // The production transport for the home, except that its dial reads the
+ // port from the scene rather than the backhaulPort seam: concurrent
+ // requests leave the transport finishing spare dials on its own
+ // goroutines, which would otherwise read the seam while fakeHomeEdge's
+ // cleanup puts it back.
+ tr := e.backhaulTransport(eip)
+ s.dialPort.Store(backhaulPort)
+ dialer := &net.Dialer{Timeout: backhaulDialTimeout}
+ tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ return dialer.DialContext(ctx, network, net.JoinHostPort(eip, s.dialPort.Load().(string)))
+ }
+ e.assets = &assetState{store: s.store, now: func() time.Time { return time.Now().Add(time.Duration(s.offset.Load())) }}
+ e.EnableUsage(s.meter)
+ s.publish(t, time.Now())
+ return s
+}
+
+// publish lands betty's edges file: laHost homed there, owned by abc/shop,
+// catching /assets/ under generation laGen, confirmed at at.
+func (s *farScene) publish(t *testing.T, at time.Time) {
+ t.Helper()
+ putJSON(t, s.m.s, "control/edges/betty.json", fmt.Sprintf(
+ `{"v":1,"box":"betty","eip":%q,"hosts":{%q:{"role":"home","account":"abc","app":"shop",`+
+ `"assets":{"paths":["/assets/"],"gen":%q,"at":%d,"primary":%q}}}}`,
+ s.eip, laHost, laGen, at.Unix(), laHost))
+ refreshHomeMap(t, s.m)
+}
+
+func (s *farScene) req(method, path string, hdr ...string) *http.Request {
+ req := httptest.NewRequest(method, "http://"+laHost+path, nil)
+ for i := 0; i+1 < len(hdr); i += 2 {
+ req.Header.Set(hdr[i], hdr[i+1])
+ }
+ return req
+}
+
+func (s *farScene) serve(req *http.Request) *httptest.ResponseRecorder {
+ rec := httptest.NewRecorder()
+ s.e.ServeHTTP(rec, req)
+ return rec
+}
+
+func (s *farScene) do(t *testing.T, method, path string, hdr ...string) *httptest.ResponseRecorder {
+ t.Helper()
+ rec := s.serve(s.req(method, path, hdr...))
+ wantNoAck(t, rec)
+ return rec
+}
+
+func (s *farScene) get(t *testing.T, path string, hdr ...string) *httptest.ResponseRecorder {
+ t.Helper()
+ return s.do(t, http.MethodGet, path, hdr...)
+}
+
+// async serves req on its own goroutine.
+func (s *farScene) async(req *http.Request) <-chan *httptest.ResponseRecorder {
+ ch := make(chan *httptest.ResponseRecorder, 1)
+ go func() { ch <- s.serve(req) }()
+ return ch
+}
+
+func (s *farScene) key(path string) assetcache.Key {
+ return assetcache.Key{Account: "abc", App: "shop", Gen: laGen, Host: laHost, Path: path}
+}
+
+func (s *farScene) row() (requests, bytes int64, ok bool) {
+ row, ok := s.meter.Drain()[laHost]
+ return row.Requests, row.BytesOut, ok
+}
+
+// fillGate holds the first request a fake home sees until release, so
+// waiters can join its fill. release is idempotent; register it with
+// t.Cleanup after the scene, so that a failing test lets the held handler
+// go before the home's server closes.
+func fillGate() (first func() bool, started chan struct{}, wait func(), release func()) {
+ started, proceed := make(chan struct{}), make(chan struct{})
+ var once sync.Once
+ var taken atomic.Bool
+ return func() bool { return taken.CompareAndSwap(false, true) }, started,
+ func() { <-proceed }, func() { once.Do(func() { close(proceed) }) }
+}
+
+func flightWaitersOf(e *Edge, id string) int {
+ f := &e.assets.flight
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if c := f.m[id]; c != nil {
+ return c.waiters
+ }
+ return 0
+}
+
+// wantNoAck: the fill's acknowledgement and expiry never reach a client.
+func wantNoAck(t *testing.T, rec *httptest.ResponseRecorder) {
+ t.Helper()
+ for _, h := range []string{assetAckHeader, assetExpiresHeader, assetFillHeader} {
+ if v := rec.Header().Values(h); len(v) > 0 {
+ t.Fatalf("the client received %s %q", h, v)
+ }
+ }
+}
+
+// ---- miss, hit, metering ----------------------------------------------------
+
+func TestFarMissFillsThenHits(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ first := s.get(t, "/assets/app.js")
+ wantCache(t, first, "miss")
+ if first.Code != 200 || first.Body.String() != laBody {
+ t.Fatalf("miss = %d %q", first.Code, first.Body.String())
+ }
+ seen := s.rec.get()
+ if seen.n != 1 || seen.hop != "1" || seen.method != http.MethodGet {
+ t.Fatalf("the home saw %d request(s), hop %q, method %q; want one GET hop", seen.n, seen.hop, seen.method)
+ }
+ if !verifyHopEitherKey(s.meshKey, nil, laHost, seen.auth, time.Now()) {
+ t.Fatalf("the fill's hop signature %q does not verify", seen.auth)
+ }
+ if _, ok := verifyAssetFill(s.meshKey, nil, laClaims("/assets/app.js"), seen.fill, time.Now()); !ok {
+ t.Fatalf("the fill's assertion %q does not verify for %+v", seen.fill, laClaims("/assets/app.js"))
+ }
+ if _, ok := s.store.Get(s.key("/assets/app.js")); !ok {
+ t.Fatal("the far edge stored nothing")
+ }
+ second := s.get(t, "/assets/app.js")
+ wantCache(t, second, "hit")
+ if second.Code != 200 || second.Body.String() != laBody {
+ t.Fatalf("hit = %d %q", second.Code, second.Body.String())
+ }
+ if n := s.rec.get().n; n != 1 {
+ t.Fatalf("the home saw %d requests, want 1", n)
+ }
+}
+
+func TestFarHitDoesNotDialTheHome(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ wantCache(t, s.get(t, "/assets/app.js"), "miss")
+ // Pooled connections to the fake home go, so any backhaul would have to
+ // dial; the dial counter now stands where the home was.
+ s.e.backhaulTransports.Range(func(_, v any) bool {
+ v.(*http.Transport).CloseIdleConnections()
+ return true
+ })
+ _, dials := e2eDialCounter(t)
+ s.dialPort.Store(backhaulPort)
+ for i := 0; i < 3; i++ {
+ wantCache(t, s.get(t, "/assets/app.js"), "hit")
+ }
+ if n := dials.Load(); n != 0 {
+ t.Fatalf("%d backhaul dial(s) for hits, want none", n)
+ }
+ if n := s.rec.get().n; n != 1 {
+ t.Fatalf("the home saw %d requests, want 1", n)
+ }
+}
+
+func TestFarAcknowledgedFillIsMeteredOnceAtTheFarEdge(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ wantCache(t, s.get(t, "/assets/app.js"), "miss")
+ wantCache(t, s.get(t, "/assets/app.js"), "hit")
+ row := s.meter.Drain()[laHost]
+ if row.Requests != 2 || row.BytesOut != int64(2*len(laBody)) {
+ t.Fatalf("row = %+v, want the fill and the hit metered once each (%d bytes each)", row, len(laBody))
+ }
+ if row.Account != "abc" || row.App != "shop" {
+ t.Fatalf("row owner = %s/%s, want the published owner abc/shop", row.Account, row.App)
+ }
+ if row.HopRequests != 0 {
+ t.Fatalf("row = %+v: the far edge's own deliveries are not hops", row)
+ }
+}
+
+func TestFarUnacknowledgedFillIsNotMeteredOrStored(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody, "X-App", "1"))
+ s.home.set(func(h *farHome) { h.ack = false })
+ for i := 0; i < 2; i++ {
+ rec := s.get(t, "/assets/app.js")
+ wantCache(t, rec, "bypass")
+ if rec.Code != 200 || rec.Body.String() != laBody || rec.Header().Get("X-App") != "1" ||
+ rec.Header().Get("Cache-Control") != "public, max-age=3600" {
+ t.Fatalf("unacknowledged = %d %q %v, want the home's response unmodified", rec.Code, rec.Body.String(), rec.Header())
+ }
+ }
+ if st := s.store.Stats(); st.Entries != 0 || st.Reserved != 0 {
+ t.Fatalf("stored an unacknowledged fill: %+v", st)
+ }
+ if n := s.rec.get().n; n != 2 {
+ t.Fatalf("the home saw %d requests, want 2", n)
+ }
+ if req, _, ok := s.row(); ok && req != 0 {
+ t.Fatalf("the far edge metered %d unacknowledged response(s); the home meters them", req)
+ }
+}
+
+// Review focus 5: a far edge whose clock is a few seconds off the home's uses
+// the home's absolute expiry as given, for a fresh home entry and for one
+// with ten minutes left of its hour (a far copy must expire when the home's
+// does, never get a lifetime of its own).
+func TestFarExpiryIsTheHomesDeadline(t *testing.T) {
+ for _, left := range []time.Duration{time.Hour, 10 * time.Minute} {
+ for _, off := range []time.Duration{5 * time.Second, -5 * time.Second} {
+ t.Run(fmt.Sprintf("left=%v/off=%v", left, off), func(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ s.offset.Store(int64(off))
+ homeExp := time.Now().Add(left).Unix()
+ s.home.set(func(h *farHome) { h.expires = func() int64 { return homeExp } })
+ wantCache(t, s.get(t, "/assets/app.js"), "miss")
+ ent, ok := s.store.Get(s.key("/assets/app.js"))
+ if !ok {
+ t.Fatal("nothing stored")
+ }
+ if got := ent.Meta.Expires.Unix(); got != homeExp {
+ t.Fatalf("stored expiry %d, want the home's %d (far clock %v off)", got, homeExp, off)
+ }
+ hit := s.get(t, "/assets/app.js")
+ wantCache(t, hit, "hit")
+ // Age is the lifetime (max-age=3600) less what is left by this
+ // edge's clock: the skew plus however much the home had used.
+ want := max(int((time.Hour-left+off)/time.Second), 0)
+ age, err := strconv.Atoi(hit.Header().Get("Age"))
+ if err != nil || age < want-2 || age > want+2 {
+ t.Fatalf("Age = %q, want about %d", hit.Header().Get("Age"), want)
+ }
+ })
+ }
+ }
+}
+
+func TestFarZeroExpiryIsMeteredNotStored(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ s.home.set(func(h *farHome) { h.expires = func() int64 { return 0 } })
+ rec := s.get(t, "/assets/app.js")
+ wantCache(t, rec, "bypass")
+ if rec.Body.String() != laBody {
+ t.Fatalf("body = %q", rec.Body.String())
+ }
+ if st := s.store.Stats(); st.Entries != 0 || st.Reserved != 0 {
+ t.Fatalf("stored a zero-expiry fill: %+v", st)
+ }
+ if req, n, _ := s.row(); req != 1 || n != int64(len(laBody)) {
+ t.Fatalf("metered %d request(s) %d bytes, want the acknowledged response once", req, n)
+ }
+}
+
+// The far edge stores under its own admission too: a home that claims a
+// response with Set-Cookie is storable is not believed.
+func TestFarOwnAdmissionStillRefuses(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody, "Set-Cookie", "a=1"))
+ rec := s.get(t, "/assets/app.js")
+ wantCache(t, rec, "bypass")
+ if st := s.store.Stats(); st.Entries != 0 {
+ t.Fatalf("stored a Set-Cookie response: %+v", st)
+ }
+ if req, _, _ := s.row(); req != 1 {
+ t.Fatalf("metered %d, want the acknowledged response once", req)
+ }
+}
+
+// D2: AssetsFor's freshness, both bounds, consumed as is.
+func TestFarStaleAtForwards(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ at time.Duration
+ caught bool
+ }{
+ {"61 minutes old", -61 * time.Minute, false},
+ {"6 minutes ahead", 6 * time.Minute, false},
+ {"4 minutes ahead", 4 * time.Minute, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ s.publish(t, time.Now().Add(tc.at))
+ rec := s.get(t, "/assets/app.js")
+ if rec.Code != 200 || rec.Body.String() != laBody {
+ t.Fatalf("= %d %q, want the home's answer", rec.Code, rec.Body.String())
+ }
+ seen := s.rec.get()
+ if tc.caught {
+ wantCache(t, rec, "miss")
+ if seen.fill == "" {
+ t.Fatal("not filled")
+ }
+ return
+ }
+ if seen.n != 1 || seen.fill != "" || seen.hop != "1" {
+ t.Fatalf("home saw n=%d fill=%q hop=%q, want one plain hop", seen.n, seen.fill, seen.hop)
+ }
+ if got := rec.Header().Get("Carlos-Cache"); got != "" {
+ t.Fatalf("Carlos-Cache = %q on a plain backhaul", got)
+ }
+ if st := s.store.Stats(); st.Entries != 0 {
+ t.Fatalf("stored %+v", st)
+ }
+ })
+ }
+}
+
+// D13: before the home map's first hosts read, no disk answer and today's
+// unresolved-host behaviour; after it, the warm entry serves.
+func TestFarServesNothingBeforeTheFirstHomeMapRead(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ wantCache(t, s.get(t, "/assets/app.js"), "miss")
+ fresh := newHomeMap(s.m.s, "annie")
+ s.e.homes.Store(fresh)
+ rec := s.get(t, "/assets/app.js")
+ if rec.Code != http.StatusNotFound || rec.Header().Get("Carlos-Cache") != "" {
+ t.Fatalf("before the first read = %d (Carlos-Cache %q), want the unknown-host 404", rec.Code, rec.Header().Get("Carlos-Cache"))
+ }
+ refreshHomeMap(t, fresh)
+ wantCache(t, s.get(t, "/assets/app.js"), "hit")
+ if n := s.rec.get().n; n != 1 {
+ t.Fatalf("the home saw %d requests, want 1", n)
+ }
+}
+
+func TestFarFillCarriesNoCookie(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ s.get(t, "/assets/app.js", "Cookie", "session=secret", "Authorization", "Bearer secret",
+ "X-Custom", "1", "User-Agent", "browser/1", "Accept", "*/*", "Accept-Encoding", "gzip",
+ "Referer", "https://elsewhere.test/")
+ h := s.rec.get().header
+ for _, name := range []string{"Cookie", "Authorization", "X-Custom", "Referer"} {
+ if v := h.Get(name); v != "" {
+ t.Errorf("the home received %s %q on a fill", name, v)
+ }
+ }
+ if h.Get("User-Agent") != "browser/1" || h.Get("Accept") != "*/*" || h.Get("Accept-Encoding") != "identity" {
+ t.Fatalf("allow-listed headers = UA %q Accept %q AE %q", h.Get("User-Agent"), h.Get("Accept"), h.Get("Accept-Encoding"))
+ }
+}
+
+func TestClientSentFillHeaderIsStripped(t *testing.T) {
+ var seenLocal atomic.Value
+ local := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ seenLocal.Store(r.Header.Get(assetFillHeader) + "|" + r.Header.Get(assetAckHeader) + "|" + r.Header.Get(assetExpiresHeader))
+ io.WriteString(w, "local")
+ }))
+ t.Cleanup(local.Close)
+ s := newFarScene(t, assetOK(laBody))
+ if err := s.e.reg.Upsert(registry.Route{Host: "local.test", Kind: "service", Addr: local.Listener.Addr().String(), Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ forged := signAssetFill(s.meshKey, laClaims("/index.html"), time.Now())
+ vocab := []string{assetFillHeader, forged, assetAckHeader, "forged", assetExpiresHeader, "4102444800"}
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "http://local.test/", nil)
+ for i := 0; i+1 < len(vocab); i += 2 {
+ req.Header.Set(vocab[i], vocab[i+1])
+ }
+ s.e.ServeHTTP(rec, req)
+ if got, _ := seenLocal.Load().(string); got != "||" {
+ t.Fatalf("a local app received the asset vocabulary %q", got)
+ }
+
+ s.get(t, "/index.html", vocab...)
+ if seen := s.rec.get(); seen.fill != "" || seen.header.Get(assetAckHeader) != "" || seen.header.Get(assetExpiresHeader) != "" {
+ t.Fatalf("a plain backhaul carried the client's vocabulary: fill %q headers %v", seen.fill, seen.header)
+ }
+
+ clientFill := signAssetFill(s.meshKey, laClaims("/assets/app.js"), time.Now().Add(-time.Second))
+ wantCache(t, s.get(t, "/assets/app.js", assetFillHeader, clientFill), "miss")
+ if seen := s.rec.get(); seen.fill == clientFill || len(seen.header.Values(assetFillHeader)) != 1 {
+ t.Fatalf("the fill carried the client's assertion: %q", seen.header.Values(assetFillHeader))
+ }
+}
+
+// The exact-remote precedence branch: this box's route catch-all would serve
+// shop.example.com, but betty homes it exactly. The second asset request is
+// a far hit, answered by neither the local backend nor the home.
+func TestFarCatchesBehindALocalWildcard(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody), "*.example.com")
+ if _, ok := s.e.lookupUpstreamPath(laHost, "/assets/app.js"); !ok {
+ t.Fatal("precondition: the local catch-all must match")
+ }
+ first := s.get(t, "/assets/app.js")
+ wantCache(t, first, "miss")
+ if first.Body.String() != laBody {
+ t.Fatalf("miss body = %q, want the home's", first.Body.String())
+ }
+ second := s.get(t, "/assets/app.js")
+ wantCache(t, second, "hit")
+ if second.Body.String() != laBody {
+ t.Fatalf("hit body = %q", second.Body.String())
+ }
+ if n := s.rec.get().n; n != 1 {
+ t.Fatalf("the home saw %d requests, want 1", n)
+ }
+ if b := s.get(t, "/assets/app.js", "X-Probe", "1").Body.String(); strings.HasPrefix(b, "xff=") {
+ t.Fatalf("the local catch-all answered a caught path: %q", b)
+ }
+}
+
+func TestDoorCallerAndVerifiedHopAreNeverCaught(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ wantCache(t, s.get(t, "/assets/app.js"), "miss")
+
+ req := s.req(http.MethodGet, "/assets/app.js")
+ req = req.WithContext(context.WithValue(req.Context(), doorCallerKey{}, doorCaller{Account: "abc", App: "shop"}))
+ door := s.serve(req)
+ if door.Header().Get("Carlos-Cache") != "" || door.Body.String() != laBody {
+ t.Fatalf("door call = %d Carlos-Cache %q %q, want the home's plain answer", door.Code, door.Header().Get("Carlos-Cache"), door.Body.String())
+ }
+ if seen := s.rec.get(); seen.n != 2 || seen.fill != "" {
+ t.Fatalf("the door call reached the home %d times (fill %q), want a plain backhaul", seen.n-1, seen.fill)
+ }
+
+ hop := s.do(t, http.MethodGet, "/assets/app.js", hopHeader, "1", hopAuthHeader, signHop(s.meshKey, laHost, time.Now()))
+ if hop.Code != http.StatusServiceUnavailable || hop.Header().Get("Carlos-Cache") != "" {
+ t.Fatalf("arrived hop = %d Carlos-Cache %q, want the stale-map refusal", hop.Code, hop.Header().Get("Carlos-Cache"))
+ }
+ if n := s.rec.get().n; n != 2 {
+ t.Fatalf("the home saw %d requests, want 2", n)
+ }
+}
+
+func TestFarUpgradeUnderAPrefixIsBackhauledIntact(t *testing.T) {
+ s := newFarScene(t, func(w http.ResponseWriter, r *http.Request) {
+ conn, buf, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+ buf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n")
+ if buf.Flush() != nil {
+ return
+ }
+ line, err := buf.ReadString('\n')
+ if err != nil {
+ return
+ }
+ buf.WriteString("home:" + line)
+ buf.Flush()
+ })
+ srv := httptest.NewServer(s.e)
+ t.Cleanup(srv.Close)
+ c, err := net.Dial("tcp", srv.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ c.SetDeadline(time.Now().Add(10 * time.Second))
+ fmt.Fprintf(c, "GET /assets/socket HTTP/1.1\r\nHost: %s\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", laHost)
+ br := bufio.NewReader(c)
+ resp, err := http.ReadResponse(br, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.StatusCode != http.StatusSwitchingProtocols || resp.Header.Get("Carlos-Cache") != "" {
+ t.Fatalf("handshake = %d Carlos-Cache %q, want an untouched 101", resp.StatusCode, resp.Header.Get("Carlos-Cache"))
+ }
+ fmt.Fprint(c, "ping\n")
+ if line, err := br.ReadString('\n'); err != nil || line != "home:ping\n" {
+ t.Fatalf("echo = %q %v", line, err)
+ }
+ seen := s.rec.get()
+ if seen.header.Get("Upgrade") != "websocket" || seen.fill != "" {
+ t.Fatalf("the home saw Upgrade %q fill %q, want the upgrade intact and no fill", seen.header.Get("Upgrade"), seen.fill)
+ }
+}
+
+// ---- the initiating request ---------------------------------------------------
+
+func TestFarColdMissAnswersARangeFromTheEntry(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody, "ETag", `"e1"`))
+ rec := s.get(t, "/assets/app.js", "Range", "bytes=0-6")
+ wantCache(t, rec, "miss")
+ if rec.Code != http.StatusPartialContent || rec.Body.String() != laBody[:7] {
+ t.Fatalf("cold range = %d %q, want 206 %q", rec.Code, rec.Body.String(), laBody[:7])
+ }
+ if got := s.rec.get().header.Get("Range"); got != "" {
+ t.Fatalf("the fill forwarded Range %q", got)
+ }
+ wantCache(t, s.get(t, "/assets/app.js"), "hit")
+ if n := s.rec.get().n; n != 1 {
+ t.Fatalf("the home saw %d requests, want 1", n)
+ }
+ if req, n, _ := s.row(); req != 2 || n != int64(7+len(laBody)) {
+ t.Fatalf("metered %d requests %d bytes, want the range and the hit as delivered", req, n)
+ }
+}
+
+func TestFarColdHeadIsBuffered(t *testing.T) {
+ t.Run("stored", func(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ rec := s.do(t, http.MethodHead, "/assets/app.js")
+ wantCache(t, rec, "miss")
+ if rec.Code != 200 || rec.Body.Len() != 0 {
+ t.Fatalf("cold HEAD = %d with %d bytes", rec.Code, rec.Body.Len())
+ }
+ if got := rec.Header().Get("ETag"); got != bodyETag(laBody) {
+ t.Fatalf("cold HEAD ETag = %q, want the fallback %q: it was not answered from the entry", got, bodyETag(laBody))
+ }
+ if m := s.rec.get().method; m != http.MethodGet {
+ t.Fatalf("the fill was a %s, want GET", m)
+ }
+ wantCache(t, s.get(t, "/assets/app.js"), "hit")
+ })
+ t.Run("unacknowledged", func(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ s.home.set(func(h *farHome) { h.ack = false })
+ rec := s.do(t, http.MethodHead, "/assets/app.js")
+ wantCache(t, rec, "bypass")
+ if rec.Code != 200 || rec.Body.Len() != 0 {
+ t.Fatalf("unacknowledged HEAD = %d with %d bytes", rec.Code, rec.Body.Len())
+ }
+ })
+}
+
+// The fallback ETag is the body's sha256 on every edge: with a real home, the
+// home's entry and the far entry carry the same value.
+func TestFarFallbackETagMatchesTheHomes(t *testing.T) {
+ var home *laScene
+ s := newFarEdge(t, func(key []byte, m *homeMap) http.Handler {
+ home = newLAScene(t, assetOK(laBody))
+ hm := newHomeMap(m.s, "betty")
+ refreshHomeMap(t, hm)
+ home.e.homes.Store(hm)
+ return home.e
+ })
+ wantCache(t, s.get(t, "/assets/app.js"), "miss")
+ homeEnt, ok := home.store.Get(home.key("/assets/app.js", ""))
+ if !ok {
+ t.Fatal("the home stored nothing")
+ }
+ farEnt, ok := s.store.Get(s.key("/assets/app.js"))
+ if !ok {
+ t.Fatal("the far edge stored nothing: the real home's acknowledgement was not accepted")
+ }
+ if h, f := homeEnt.Meta.Header.Get("ETag"), farEnt.Meta.Header.Get("ETag"); h != f || f != bodyETag(laBody) {
+ t.Fatalf("home ETag %q, far ETag %q, want both %q", h, f, bodyETag(laBody))
+ }
+ if homeEnt.Meta.Expires.Unix() != farEnt.Meta.Expires.Unix() {
+ t.Fatalf("home expiry %v, far expiry %v", homeEnt.Meta.Expires, farEnt.Meta.Expires)
+ }
+}
+
+// ---- coalescing ---------------------------------------------------------------
+
+func TestFarCoalescedWaitersGetTheEntry(t *testing.T) {
+ first, started, hold, release := fillGate()
+ s := newFarScene(t, func(w http.ResponseWriter, r *http.Request) {
+ if first() {
+ close(started)
+ hold()
+ }
+ assetOK(laBody)(w, r)
+ })
+ t.Cleanup(release)
+ leader := s.async(s.req(http.MethodGet, "/assets/app.js"))
+ <-started
+ var waiters []<-chan *httptest.ResponseRecorder
+ for i := 0; i < 3; i++ {
+ waiters = append(waiters, s.async(s.req(http.MethodGet, "/assets/app.js")))
+ }
+ id := s.key("/assets/app.js").ID()
+ laWaitFor(t, "three waiters", func() bool { return flightWaitersOf(s.e, id) == 3 })
+ release()
+ lead := <-leader
+ wantNoAck(t, lead)
+ wantCache(t, lead, "miss")
+ if lead.Body.String() != laBody {
+ t.Fatalf("leader body = %q", lead.Body.String())
+ }
+ for _, ch := range waiters {
+ rec := <-ch
+ wantNoAck(t, rec)
+ wantCache(t, rec, "hit")
+ if rec.Body.String() != laBody {
+ t.Fatalf("waiter body = %q", rec.Body.String())
+ }
+ }
+ if n := s.rec.get().n; n != 1 {
+ t.Fatalf("the home saw %d requests, want 1", n)
+ }
+ if req, n, _ := s.row(); req != 4 || n != int64(4*len(laBody)) {
+ t.Fatalf("metered %d requests %d bytes, want every delivery once", req, n)
+ }
+}
+
+func TestFarRefusedFillReachesOnlyTheInitiator(t *testing.T) {
+ for _, mode := range []string{"set-cookie", "unacknowledged"} {
+ t.Run(mode, func(t *testing.T) {
+ first, started, hold, release := fillGate()
+ s := newFarScene(t, func(w http.ResponseWriter, r *http.Request) {
+ if first() {
+ close(started)
+ hold()
+ }
+ acc := r.Header.Get("Accept")
+ w.Header().Set("Content-Type", "application/javascript")
+ w.Header().Set("Cache-Control", "public, max-age=3600")
+ w.Header().Set("Set-Cookie", "for="+acc)
+ io.WriteString(w, "for "+acc)
+ })
+ t.Cleanup(release)
+ if mode == "unacknowledged" {
+ s.home.set(func(h *farHome) { h.ack = false })
+ } else {
+ s.home.set(func(h *farHome) { h.expires = func() int64 { return 0 } })
+ }
+ leader := s.async(s.req(http.MethodGet, "/assets/app.js", "Accept", "text/a0"))
+ <-started
+ var waiters []<-chan *httptest.ResponseRecorder
+ for i := 1; i <= 3; i++ {
+ waiters = append(waiters, s.async(s.req(http.MethodGet, "/assets/app.js", "Accept", fmt.Sprintf("text/a%d", i))))
+ }
+ id := s.key("/assets/app.js").ID()
+ laWaitFor(t, "three waiters", func() bool { return flightWaitersOf(s.e, id) == 3 })
+ release()
+ check := func(rec *httptest.ResponseRecorder, i int) {
+ t.Helper()
+ wantNoAck(t, rec)
+ wantCache(t, rec, "bypass")
+ want := fmt.Sprintf("text/a%d", i)
+ if rec.Body.String() != "for "+want || rec.Header().Get("Set-Cookie") != "for="+want {
+ t.Fatalf("client %d got %q with Set-Cookie %q: another client's response", i, rec.Body.String(), rec.Header().Get("Set-Cookie"))
+ }
+ }
+ check(<-leader, 0)
+ for i, ch := range waiters {
+ check(<-ch, i+1)
+ }
+ seen := s.rec.get()
+ if seen.n != 4 {
+ t.Fatalf("the home saw %d requests, want each client's own", seen.n)
+ }
+ got := map[string]bool{}
+ for _, a := range seen.accepts {
+ got[a] = true
+ }
+ for i := 0; i <= 3; i++ {
+ if !got[fmt.Sprintf("text/a%d", i)] {
+ t.Fatalf("the home never saw client %d's request: %q", i, seen.accepts)
+ }
+ }
+ if st := s.store.Stats(); st.Entries != 0 {
+ t.Fatalf("stored %+v", st)
+ }
+ wantReq := int64(1) // the acknowledged leader; the waiters' plain hops are the home's
+ if mode == "unacknowledged" {
+ wantReq = 0
+ }
+ if req, _, _ := s.row(); req != wantReq {
+ t.Fatalf("metered %d requests at the far edge, want %d", req, wantReq)
+ }
+ })
+ }
+}
+
+// ---- headers and trailers the client must not see -----------------------------
+
+// The home's own Carlos-Cache is replaced, and the asset vocabulary never
+// reaches a client as a trailer, announced or not, acknowledged or not.
+func TestFarReservedTrailersNeverReachTheClient(t *testing.T) {
+ reserved := []string{assetAckHeader, assetExpiresHeader, assetCacheHeader, assetFillHeader}
+ for _, ack := range []bool{true, false} {
+ for _, announced := range []bool{true, false} {
+ t.Run(fmt.Sprintf("ack=%v/announced=%v", ack, announced), func(t *testing.T) {
+ s := newFarScene(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/javascript")
+ w.Header().Set("Cache-Control", "public, max-age=3600")
+ w.Header().Set("Carlos-Cache", "hit")
+ if announced {
+ w.Header().Set("Trailer", strings.Join(append([]string{"X-Kept"}, reserved...), ", "))
+ }
+ io.WriteString(w, laBody)
+ w.(http.Flusher).Flush()
+ prefix := ""
+ if !announced {
+ prefix = http.TrailerPrefix
+ }
+ w.Header().Set(prefix+"X-Kept", "1")
+ for _, h := range reserved {
+ w.Header().Set(prefix+h, "forged")
+ }
+ })
+ s.home.set(func(h *farHome) { h.ack = ack })
+ front := httptest.NewServer(s.e)
+ t.Cleanup(front.Close)
+ req, err := http.NewRequest(http.MethodGet, front.URL+"/assets/app.js", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = laHost
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if b, _ := io.ReadAll(resp.Body); string(b) != laBody {
+ t.Fatalf("body = %q", b)
+ }
+ want := "bypass"
+ if ack {
+ want = "miss"
+ }
+ if got := resp.Header.Get("Carlos-Cache"); got != want {
+ t.Fatalf("Carlos-Cache = %q, want this edge's %q", got, want)
+ }
+ for _, h := range reserved {
+ if _, ok := resp.Trailer[http.CanonicalHeaderKey(h)]; ok {
+ t.Errorf("the client received the %s trailer: %v", h, resp.Trailer)
+ }
+ for _, v := range resp.Header.Values("Trailer") {
+ if strings.Contains(strings.ToLower(v), strings.ToLower(h)) {
+ t.Errorf("the response announces the %s trailer: %q", h, v)
+ }
+ }
+ if h != assetCacheHeader && resp.Header.Get(h) != "" {
+ t.Errorf("the client received the %s header", h)
+ }
+ }
+ if got := resp.Trailer.Get("X-Kept"); got != "1" {
+ t.Errorf("X-Kept trailer = %q, want 1 (trailers %v)", got, resp.Trailer)
+ }
+ })
+ }
+ }
+}
+
+// ---- admission around the far catch (drift D8, D10) ---------------------------
+
+// A far hit spends the owner's account throttle like any delivery (D8).
+func TestFarHitsPassThePlanThrottle(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ frozen := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)
+ s.e.planLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000)
+ var on atomic.Bool
+ s.e.SetPlanThrottleFor(func(rt registry.Route) (plans.Throttle, bool) {
+ if !on.Load() || rt.Account != "abc" || rt.Kind != "instance" {
+ return plans.Throttle{}, false
+ }
+ return plans.Throttle{Bandwidth: true, Until: frozen.Add(time.Hour)}, true
+ })
+ wantCache(t, s.get(t, "/assets/app.js"), "miss")
+ s.meter.Drain()
+ on.Store(true)
+ refused := 0
+ for i := 0; i <= plans.ThrottleRule.Burst; i++ {
+ if rec := s.get(t, "/assets/app.js"); rec.Code == http.StatusTooManyRequests {
+ refused++
+ } else {
+ wantCache(t, rec, "hit")
+ }
+ }
+ if refused != 1 {
+ t.Fatalf("%d far hits refused past the throttle's burst, want 1", refused)
+ }
+ row := s.meter.Drain()[laHost]
+ if row.PlanThrottled != 1 || row.Requests != int64(plans.ThrottleRule.Burst+1) {
+ t.Fatalf("row = %+v, want one plan-throttle refusal and every answer metered", row)
+ }
+ if n := s.rec.get().n; n != 1 {
+ t.Fatalf("the home saw %d requests, want 1", n)
+ }
+}
+
+// A far fill holds a backhaul slot; a saturated hop is answered 503 with
+// Retry-After: 2, with no dial (D10).
+func TestFarFillHoldsABackhaulSlot(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ old := backhaulMaxInflight.Load()
+ backhaulMaxInflight.Store(0)
+ t.Cleanup(func() { backhaulMaxInflight.Store(old) })
+ rec := s.get(t, "/assets/app.js")
+ if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") != "2" {
+ t.Fatalf("saturated fill = %d Retry-After %q, want 503 and 2", rec.Code, rec.Header().Get("Retry-After"))
+ }
+ if n := s.rec.get().n; n != 0 {
+ t.Fatalf("the home saw %d requests, want none", n)
+ }
+ backhaulMaxInflight.Store(old)
+ wantCache(t, s.get(t, "/assets/app.js"), "miss")
+ if v, ok := s.e.backhaulInflight.Load("betty"); !ok || v.(*atomic.Int64).Load() != 0 {
+ t.Fatal("the fill's backhaul slot was not given back")
+ }
+}
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go
index 81ff62807..e57c7f174 100644
--- a/internal/edge/assetcatch.go
+++ b/internal/edge/assetcatch.go
@@ -17,6 +17,7 @@ import (
"github.com/carlosframework/platform/internal/assetcache"
"github.com/carlosframework/platform/internal/geoip"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
@@ -298,7 +299,9 @@ func (e *Edge) serveAssetLocal(w http.ResponseWriter, r *http.Request, host stri
done(nil)
return true
}
- e.leadAssetFill(w, r, up, k, a, release, done, nil, nil)
+ e.leadAssetFill(w, r, release, done, func(ctx context.Context, onHeader func(assetVerdict, http.Header)) (*assetcache.Entry, error) {
+ return e.fillFromApp(ctx, w, r, up, k, onHeader)
+ }, nil, func() { e.assetForward(w, r, up, nil) })
return true
}
@@ -382,7 +385,9 @@ func (e *Edge) serveAssetFillForHop(w http.ResponseWriter, r *http.Request, host
return true
}
unack(w.Header())
- e.leadAssetFill(w, r, up, k, a, release, done, func(v assetVerdict, h http.Header) {
+ e.leadAssetFill(w, r, release, done, func(ctx context.Context, onHeader func(assetVerdict, http.Header)) (*assetcache.Entry, error) {
+ return e.fillFromApp(ctx, w, r, up, k, onHeader)
+ }, func(v assetVerdict, h http.Header) {
// The expiry is the header-time storability verdict (§5.3), not a
// claim that this home's own commit will succeed: the far edge stores
// under its own admission, size, trailer and reservation checks.
@@ -391,7 +396,7 @@ func (e *Edge) serveAssetFillForHop(w http.ResponseWriter, r *http.Request, host
exp = v.Expires.Unix()
}
ack(h, exp)
- }, unstorable)
+ }, func() { e.assetForward(w, r, up, unstorable) })
return true
}
@@ -466,6 +471,12 @@ func (a *assetResultWriter) Flush() {
func (a *assetResultWriter) Unwrap() http.ResponseWriter { return a.ResponseWriter }
+// assetFillFunc runs one fill for a flight's leader: fillFromApp on a box
+// that holds the route, fillFromHome on a far edge. onHeader is called before
+// the first body byte with the verdict and the header map about to be written
+// to the initiator.
+type assetFillFunc func(ctx context.Context, onHeader func(assetVerdict, http.Header)) (*assetcache.Entry, error)
+
// leadAssetFill runs the fill a flight's leader owes and answers r from it.
// release is the rate-limit slot the caller was admitted with (nil for none):
// it goes back at the upstream's first final response, as slotWriter gives
@@ -473,14 +484,15 @@ func (a *assetResultWriter) Unwrap() http.ResponseWriter { return a.ResponseWrit
// verdict refuses, at the deadline when the fill is abandoned (so waiters
// are forwarded then, not when the stream ends), and with the entry when
// it commits. onHeader, when set, edits the initiator's headers at header
-// time; onForward, when set, edits them on a re-forward.
+// time. forward is the uncached fallback that answers the initiator when the
+// fill could not.
//
// A buffered initiator is answered from the entry it waited for ("miss"),
// or, when nothing was stored and nothing was written to it, forwarded
// again as an ordinary request; it is metered once, for the one delivery.
// A streamed initiator has had its answer already.
-func (e *Edge) leadAssetFill(w http.ResponseWriter, r *http.Request, up upstream, k assetcache.Key, a HostAssets,
- release func(), done func(*assetcache.Entry), onHeader func(assetVerdict, http.Header), onForward func(http.Header)) {
+func (e *Edge) leadAssetFill(w http.ResponseWriter, r *http.Request, release func(), done func(*assetcache.Entry),
+ fill assetFillFunc, onHeader func(assetVerdict, http.Header), forward func()) {
defer done(nil)
if release != nil {
defer release()
@@ -489,7 +501,7 @@ func (e *Edge) leadAssetFill(w http.ResponseWriter, r *http.Request, up upstream
defer cancel()
stop := context.AfterFunc(ctx, func() { done(nil) })
defer stop()
- ent, err := e.fillFromApp(ctx, w, r, up, k, a, func(v assetVerdict, h http.Header) {
+ ent, err := fill(ctx, func(v assetVerdict, h http.Header) {
if release != nil {
release()
}
@@ -507,9 +519,9 @@ func (e *Edge) leadAssetFill(w http.ResponseWriter, r *http.Request, up upstream
if serveAssetEntry(w, r, ent, e.assets.clock(), "miss") == nil {
return
}
- e.assetForward(w, r, up, onForward)
+ forward()
case ent == nil && errors.Is(err, errAssetUndelivered):
- e.assetForward(w, r, up, onForward)
+ forward()
case errors.Is(err, errAssetBrokeOff):
// As httputil.ReverseProxy does for a body that breaks off: abort
// the client's response so it is not taken for a complete one.
@@ -522,13 +534,35 @@ func (e *Edge) leadAssetFill(w http.ResponseWriter, r *http.Request, up upstream
// fillFromApp fills k from the app (§5.2, §5.3). It sends the allow-listed
// request (Host, User-Agent, Accept, Accept-Encoding: identity; GET even for
// a HEAD; no cookie, no credentials, no visitor geo) through the activator
-// for a hibernating route or up.proxy otherwise, judges the response with
+// for a hibernating route or up.proxy otherwise, and judges the response with
// assetAdmit when its headers arrive (declared by the build that answered:
// the generation's X-Carlos-Version on a generation-managed route, the
-// route's Version otherwise, asked of the policy with the request
-// hostname), calls onHeader before the first body byte with the verdict and
-// the header map about to be written to w, and writes the body into a Fill
-// while the verdict says store, hashing it with SHA-256.
+// route's Version otherwise, asked of the policy with the request hostname).
+// The rest is runAssetFill.
+func (e *Edge) fillFromApp(ctx context.Context, w http.ResponseWriter, r *http.Request, up upstream, k assetcache.Key, onHeader func(v assetVerdict, h http.Header)) (*assetcache.Entry, error) {
+ st := e.assets
+ judge := func(code int, snap http.Header, reqTime, respTime time.Time) assetVerdict {
+ build := up.route.Version
+ if up.genManaged {
+ build = snap.Get("X-Carlos-Version")
+ }
+ return assetAdmit(code, snap, reqTime, respTime, st.local.Declared(k.Host, build, r.URL.Path))
+ }
+ send := func(w http.ResponseWriter, req *http.Request) {
+ if up.hibernating && e.act.ServeHTTP(w, req, up.route, up.proxy) {
+ return
+ }
+ up.proxy.ServeHTTP(w, req)
+ }
+ return e.runAssetFill(ctx, w, r, k, up.route.Host, judge, send, onHeader)
+}
+
+// runAssetFill is one fill of k, from the app or from the home box: it sends
+// the allow-listed request (assetFillRequest) with send, judges the
+// response with judge when its headers arrive, calls onHeader before the
+// first body byte with the verdict and the header map about to be written to
+// w, and writes the body into a Fill while the verdict says store, hashing it
+// with SHA-256. origin names the route in a commit failure's log line.
//
// The initiating request r decides what w gets (assetBuffered): a streamed
// initiator is teed the response as it comes, answered miss when it is being
@@ -545,19 +579,21 @@ func (e *Edge) leadAssetFill(w http.ResponseWriter, r *http.Request, up upstream
// their entry; it is cancelled once nobody needs its bytes.
//
// On success the stored header gains a strong ETag of the body's hex
-// sha256 when the app sent none (§5.4), and the fill commits. It returns
+// sha256 when the upstream sent none (§5.4), and the fill commits. It returns
// the entry as the store then holds it. A Commit error is returned beside
// whatever Get then shows (drift D5: the entry may be published even so),
// never taken as a rollback. Without an entry the error says whether the
// initiator was answered: errAssetUndelivered when nothing was written to
// it, errAssetBrokeOff when its streamed body broke off, errAssetNotStored
// otherwise.
-func (e *Edge) fillFromApp(ctx context.Context, w http.ResponseWriter, r *http.Request, up upstream, k assetcache.Key, a HostAssets, onHeader func(v assetVerdict, h http.Header)) (*assetcache.Entry, error) {
+func (e *Edge) runAssetFill(ctx context.Context, w http.ResponseWriter, r *http.Request, k assetcache.Key, origin string,
+ judge func(code int, snap http.Header, reqTime, respTime time.Time) assetVerdict,
+ send func(http.ResponseWriter, *http.Request), onHeader func(v assetVerdict, h http.Header)) (*assetcache.Entry, error) {
st := e.assets
upCtx, upCancel := context.WithCancel(context.WithValue(context.WithoutCancel(ctx), geoResultKey{}, geoip.Off()))
defer upCancel()
fw := &assetFillWriter{
- e: e, st: st, w: w, r: r, up: up, k: k, a: a,
+ e: e, st: st, w: w, r: r, k: k, origin: origin, judge: judge, send: send,
buffered: assetBuffered(r), head: r.Method == http.MethodHead,
onHeader: onHeader, cancelUp: upCancel,
hdr: http.Header{}, hash: sha256.New(), cl: -1, reqTime: st.clock(),
@@ -605,9 +641,10 @@ type assetFillWriter struct {
st *assetState
w http.ResponseWriter // the initiator's writer
r *http.Request // the initiating request
- up upstream
k assetcache.Key
- a HostAssets
+ origin string // the route a commit failure is logged for
+ judge func(code int, snap http.Header, reqTime, respTime time.Time) assetVerdict
+ send func(http.ResponseWriter, *http.Request)
buffered bool
head bool
onHeader func(assetVerdict, http.Header)
@@ -644,10 +681,7 @@ func (fw *assetFillWriter) dispatch(req *http.Request) (brokeOff bool) {
brokeOff = true
}
}()
- if fw.up.hibernating && fw.e.act.ServeHTTP(fw, req, fw.up.route, fw.up.proxy) {
- return false
- }
- fw.up.proxy.ServeHTTP(fw, req)
+ fw.send(fw, req)
return false
}
@@ -660,12 +694,7 @@ func (fw *assetFillWriter) WriteHeader(code int) {
fw.wrote = true
respTime := fw.st.clock()
fw.snap = fw.hdr.Clone()
- build := fw.up.route.Version
- if fw.up.genManaged {
- build = fw.snap.Get("X-Carlos-Version")
- }
- declared := fw.st.local.Declared(fw.k.Host, build, fw.r.URL.Path)
- v := assetAdmit(code, fw.snap, fw.reqTime, respTime, declared)
+ v := fw.judge(code, fw.snap, fw.reqTime, respTime)
fw.verdict = v
if s := strings.TrimSpace(fw.snap.Get("Content-Length")); s != "" {
if n, err := strconv.ParseInt(s, 10, 64); err == nil && n >= 0 {
@@ -843,8 +872,8 @@ func (fw *assetFillWriter) finish(brokeOff bool) (*assetcache.Entry, error) {
cerr := fill.Commit(assetcache.Meta{Header: hdr, Lifetime: fw.verdict.Lifetime, Expires: fw.verdict.Expires}, fw.verdict.Gzip)
if cerr != nil {
fill.Abort() // a no-op once Commit has settled the fill; never a rollback
- fw.e.logThrottled("asset-commit "+fw.up.route.Host, fmt.Sprintf(
- "asset cache: storing %s%s for %s failed: %v", fw.k.Host, fw.k.Path, fw.up.route.Host, cerr))
+ fw.e.logThrottled("asset-commit "+fw.origin, fmt.Sprintf(
+ "asset cache: storing %s%s for %s failed: %v", fw.k.Host, fw.k.Path, fw.origin, cerr))
}
ent, ok := fw.st.store.Get(fw.k)
if !ok {
@@ -917,3 +946,263 @@ func stripAssetTrailers(resp *http.Response) {
}
}}
}
+
+// ---- serving on a box without the route (§5.1, §5.3, §8) -------------------
+
+// farAssetCatch is the catch decision on a box with no local route row for
+// host (§5.1): armed, GET or HEAD and not an upgrade, neither a verified hop
+// nor a door caller (both keep their own paths), the home map's published
+// answer for host (AssetsFor: an exact key, the first hosts read done, and
+// the authority time within the hour and at most five minutes ahead, drift
+// D2 and D13), a path under one of its prefixes, the exact home the answer
+// came from, and a mirrored mesh key to sign with. The canonical-path check
+// comes later: a request that fails it is still under a prefix, and is
+// answered bypass.
+func (e *Edge) farAssetCatch(r *http.Request, host string) (a HostAssets, eip, box string, key []byte, ok bool) {
+ st := e.assets
+ if st == nil || st.store == nil {
+ return HostAssets{}, "", "", nil, false
+ }
+ if (r.Method != http.MethodGet && r.Method != http.MethodHead) || isUpgradeRequest(r) {
+ return HostAssets{}, "", "", nil, false
+ }
+ if _, door := doorCallerFrom(r.Context()); door || hopVerified(r.Context()) {
+ return HostAssets{}, "", "", nil, false
+ }
+ m := e.homes.Load()
+ a, ok = m.AssetsFor(host, st.clock())
+ if !ok || !assetPrefixMatch(a.Paths, r.URL.Path) {
+ return HostAssets{}, "", "", nil, false
+ }
+ if eip, box, ok = m.ExactHome(host); !ok {
+ return HostAssets{}, "", "", nil, false
+ }
+ if key = signingKey(m.meshKeys()); len(key) == 0 {
+ return HostAssets{}, "", "", nil, false
+ }
+ return a, eip, box, key, true
+}
+
+// serveAssetFar is the far catch (§5.1, §5.3): called on both forwarding
+// paths, the exact-remote precedence branch and the lookup-miss branch, just
+// before the backhaul each would make. It reports whether it answered; false
+// leaves the request to that backhaul exactly as before.
+//
+// A hit is answered from this box's store. A miss leads or joins a flight;
+// the leader asks the home box for a signed fill over the backhaul
+// (fillFromHome) under a backhaul slot (backhaulAcquire with the initiating
+// client's fair-share key, drift D10), and answers its client from that fill
+// by Task 5's initiating-request rule. A waiter whose flight stored nothing,
+// a non-canonical path and an initiator the fill could not answer are
+// forwarded as an ordinary backhaul and answered bypass.
+//
+// Usage (§8): this edge meters what it delivers itself (hits, and every
+// response carrying a valid acknowledgement of its own assertion, storable
+// or not) once, under the published owner. A response the home did not
+// acknowledge was metered by the home, and is not metered here. The rate
+// limit applies at the home, which the fill reaches as a hop (D7); the
+// owner's account throttle applies here, to every delivery this edge answers
+// itself, with a synthetic instance route (D8).
+func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string) bool {
+ a, eip, box, key, ok := e.farAssetCatch(r, host)
+ if !ok {
+ return false
+ }
+ forward := func() { e.farForward(w, r, host, eip, box) }
+ if !canonicalAssetPath(r.URL) {
+ forward()
+ return true
+ }
+ st := e.assets
+ rt := registry.Route{Host: host, Account: a.Account, App: a.App, Kind: "instance"}
+ var n int64
+ cw := &countingWriter{ResponseWriter: w, n: &n}
+ var billed, acked, reforwarded bool
+ defer func() {
+ if billed || (acked && !reforwarded) {
+ if m := e.usageMeter.Load(); m != nil {
+ m.Record(rt, 1, n, false)
+ }
+ }
+ }()
+ var judged, admitted bool
+ throttle := func() bool {
+ if !judged {
+ judged = true
+ admitted = e.planThrottleAdmit(cw, r, upstream{route: rt})
+ billed = !admitted
+ }
+ return admitted
+ }
+ hit := func(ent *assetcache.Entry) bool {
+ if !throttle() {
+ return true
+ }
+ if serveAssetEntry(cw, r, ent, st.clock(), "hit") == nil {
+ billed = true
+ return true
+ }
+ return false
+ }
+ k := assetKey(a, host, r.URL)
+ if ent, ok := st.store.Get(k); ok && hit(ent) {
+ return true
+ }
+ leader, wait, done := st.flight.join(k.ID())
+ if !leader {
+ if ent, ok := wait(r.Context()); ok && hit(ent) {
+ return true
+ }
+ forward()
+ return true
+ }
+ if !throttle() {
+ done(nil)
+ return true
+ }
+ assertion := signAssetFill(key, assetFillClaims{
+ Host: host, PathQuery: assetPathQuery(r.URL), Account: a.Account, App: a.App, Gen: a.Gen,
+ }, time.Now())
+ if assertion == "" {
+ done(nil)
+ forward()
+ return true
+ }
+ releaseSlot, ok, shed := e.backhaulAcquire(box, e.backhaulClientKey(r))
+ if shed {
+ done(nil)
+ writeRateLimited(w, time.Second)
+ return true
+ }
+ if !ok {
+ done(nil)
+ e.logThrottled("backhaul-saturated "+box,
+ fmt.Sprintf("backhaul to %s (%s) is at its in-flight cap (%d) — answering 503 + Retry-After: 2", box, eip, backhaulMaxInflight.Load()))
+ w.Header().Set("Retry-After", "2")
+ http.Error(w, "temporarily busy", http.StatusServiceUnavailable)
+ return true
+ }
+ e.leadAssetFill(cw, r, nil, done, func(ctx context.Context, onHeader func(assetVerdict, http.Header)) (*assetcache.Entry, error) {
+ // The slot is held for the fill's whole exchange with the home, and
+ // given back before any re-forward takes its own.
+ defer releaseSlot()
+ return e.fillFromHome(ctx, cw, r, k, host, eip, box, key, assertion, &acked, onHeader)
+ }, func(_ assetVerdict, h http.Header) { stripAssetFillVocabulary(h) }, func() {
+ reforwarded = true
+ forward()
+ })
+ return true
+}
+
+// fillFromHome is a far edge's fill of k from the home box at eip (§5.3): the
+// allow-listed request (assetFillRequest, so no cookie and no credentials)
+// sent over the backhaul as a signed hop carrying X-Carlos-Asset-Fill. The
+// response is storable only when it carries a valid acknowledgement of that
+// assertion with a non-zero X-Carlos-Asset-Expires, and passes this edge's
+// own header-time admission too; the entry then expires at the home's
+// absolute expiry, unchanged (never recomputed from this edge's clock), so a
+// copy of a nearly expired home entry expires when the home's does. acked is
+// set when the acknowledgement verifies, storable or not: the caller meters
+// exactly those responses. The rest (body size, reservation, trailer veto,
+// fallback ETag, the initiating-request rule) is runAssetFill's, as for a
+// fill from the app.
+func (e *Edge) fillFromHome(ctx context.Context, w http.ResponseWriter, r *http.Request, k assetcache.Key, host, eip, box string,
+ key []byte, assertion string, acked *bool, onHeader func(assetVerdict, http.Header)) (*assetcache.Entry, error) {
+ judge := func(code int, snap http.Header, reqTime, respTime time.Time) assetVerdict {
+ exp, ok := assetAcknowledged(snap, key, assertion)
+ if !ok {
+ return assetRefuse("unacknowledged")
+ }
+ *acked = true
+ if exp == 0 {
+ return assetRefuse("home-refused")
+ }
+ v := assetAdmit(code, snap, reqTime, respTime, true)
+ if !v.Store {
+ return v
+ }
+ v.Expires = time.Unix(exp, 0)
+ // Already expired here, or further out than the lifetime the
+ // response itself declares (plus the hop's clock window): served,
+ // not stored.
+ if !v.Expires.After(respTime) || v.Expires.After(respTime.Add(v.Lifetime+hopSkew)) {
+ return assetRefuse("expiry")
+ }
+ return v
+ }
+ send := func(w http.ResponseWriter, req *http.Request) {
+ req.Header.Set(assetFillHeader, assertion)
+ backhaulProxy(host, eip, box, signHop(key, host, time.Now()), "", e.backhaulTransport(eip), e.logThrottled).ServeHTTP(w, req)
+ }
+ return e.runAssetFill(ctx, w, r, k, host, judge, send, onHeader)
+}
+
+// assetAcknowledged reads a home's acknowledgement of assertion from response
+// headers h: exactly one X-Carlos-Asset-Expires, a non-negative decimal, and
+// exactly one X-Carlos-Asset-Fill-Ack that verifies under key for both.
+func assetAcknowledged(h http.Header, key []byte, assertion string) (expires int64, ok bool) {
+ exps, acks := h.Values(assetExpiresHeader), h.Values(assetAckHeader)
+ if len(exps) != 1 || len(acks) != 1 {
+ return 0, false
+ }
+ exp, err := strconv.ParseInt(strings.TrimSpace(exps[0]), 10, 64)
+ if err != nil || exp < 0 || !verifyAssetAck(key, assertion, exp, strings.TrimSpace(acks[0])) {
+ return 0, false
+ }
+ return exp, true
+}
+
+// farForward is the far catch's uncached fallback: the ordinary backhaul,
+// answered Carlos-Cache: bypass. The backhaul proxy does not pass through
+// responseModifier, so the asset vocabulary is kept off the client's response
+// here, headers and trailers both. backhaulTo answers false only when the mesh
+// key went away after farAssetCatch read it; the client is then told to come
+// back shortly rather than given an answer for a host this box does not
+// serve.
+func (e *Edge) farForward(w http.ResponseWriter, r *http.Request, host, eip, box string) {
+ aw := &assetResultWriter{ResponseWriter: w, result: "bypass", onHeader: stripAssetFillVocabulary}
+ if !e.backhaulTo(aw, r, host, eip, box) {
+ w.Header().Set("Retry-After", "2")
+ http.Error(w, "temporarily busy", http.StatusServiceUnavailable)
+ }
+ stripAssetTrailerValues(w.Header())
+}
+
+// stripAssetFillVocabulary deletes the fill's request and acknowledgement
+// headers from a response header map about to be written, and takes every
+// asset-vocabulary name out of its Trailer announcement, so a value sent
+// later under that name is not a trailer the client receives. Carlos-Cache,
+// set by this edge, stays.
+func stripAssetFillVocabulary(h http.Header) {
+ h.Del(assetFillHeader)
+ h.Del(assetAckHeader)
+ h.Del(assetExpiresHeader)
+ vs := h.Values("Trailer")
+ if len(vs) == 0 {
+ return
+ }
+ var keep []string
+ for _, v := range vs {
+ for _, name := range strings.Split(v, ",") {
+ if name = strings.TrimSpace(name); name != "" && !isAssetVocabulary(name) {
+ keep = append(keep, name)
+ }
+ }
+ }
+ h.Del("Trailer")
+ if len(keep) > 0 {
+ h.Set("Trailer", strings.Join(keep, ", "))
+ }
+}
+
+// stripAssetTrailerValues deletes unannounced asset-vocabulary trailers
+// (http.TrailerPrefix keys) a proxy left in a handler's header map, before
+// the handler returns and the server sends them.
+func stripAssetTrailerValues(h http.Header) {
+ for k := range h {
+ if len(k) > len(http.TrailerPrefix) && strings.EqualFold(k[:len(http.TrailerPrefix)], http.TrailerPrefix) &&
+ isAssetVocabulary(k[len(http.TrailerPrefix):]) {
+ delete(h, k)
+ }
+ }
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 9c48190f3..cbd4ae056 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -1571,6 +1571,17 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// On a request carrying no X-Carlos-Hop this is one Header.Get and
// nothing else.
r, hopped := e.acceptHop(r, host)
+ // The asset cache's fill vocabulary (assetcatch.go, design §5.3) is this
+ // edge's to send, never a client's: a far edge's assertion is honoured
+ // only on a verified hop, where the home's fill hook consumes it, and no
+ // inbound request may carry an acknowledgement or an expiry. Deleted here,
+ // before every branch below, so neither an app nor a home box is ever
+ // handed a value a client made up.
+ r.Header.Del(assetAckHeader)
+ r.Header.Del(assetExpiresHeader)
+ if !hopped {
+ r.Header.Del(assetFillHeader)
+ }
// GeoIP steps 3-4 (geoip spec §8.1, §8.2): decide once, keep it on the
// context for setGeo and analytics, and expose the app-visible headers on
// r.Header so the cache's Vary matching sees exactly what the app will
@@ -1593,9 +1604,15 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// elsewhere — for every request that landed here. An arrived hop and a
// door call keep the local answer: neither may start a backhaul of its
// own here.
+ //
+ // The far asset catch (assetcatch.go, design §5.1) runs on this path too,
+ // just before the dial: the name is homed elsewhere, so its declared asset
+ // paths are answered from this box's store or filled from that home.
if ok && !hopped && !isDoor && !e.servesExactly(host) {
- if eip, box, remote := e.homes.Load().ExactHome(host); remote && e.backhaulTo(w, r, host, eip, box) {
- return
+ if eip, box, remote := e.homes.Load().ExactHome(host); remote {
+ if e.serveAssetFar(w, r, host) || e.backhaulTo(w, r, host, eip, box) {
+ return
+ }
}
}
if !ok {
@@ -1628,7 +1645,13 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// may (backhaul, below). It answers false when no box homes the host,
// or when nothing could prove the hop, and today's unknown-host answer
// then follows exactly as it always has.
- if e.backhaul(w, r, host) {
+ //
+ // First the far asset catch (assetcatch.go, design §5.1): a declared
+ // asset path of a host another box homes is answered from this box's
+ // store, or filled from the home by a signed backhaul. Below the two
+ // returns above, so a verified hop and a door caller never reach it;
+ // it excludes upgrades itself, since the upgrade branch is further on.
+ if e.serveAssetFar(w, r, host) || e.backhaul(w, r, host) {
return
}
e.unknownHost(w, r)
diff --git a/internal/edge/homemap_test.go b/internal/edge/homemap_test.go
index e5d9ef0fe..f8db2bc49 100644
--- a/internal/edge/homemap_test.go
+++ b/internal/edge/homemap_test.go
@@ -679,6 +679,13 @@ type homeEdgeSeen struct {
sni, host, hop, auth string
proof string
xff []string
+ // For the asset cache's far fill (asset_far_test.go): the last request's
+ // method, its X-Carlos-Asset-Fill and all of its headers, and the Accept
+ // of every request in arrival order.
+ method string
+ fill string
+ header http.Header
+ accepts []string
}
type homeEdgeRecord struct {
@@ -689,7 +696,10 @@ type homeEdgeRecord struct {
func (h *homeEdgeRecord) get() homeEdgeSeen {
h.mu.Lock()
defer h.mu.Unlock()
- return h.seen
+ seen := h.seen
+ seen.header = h.seen.header.Clone()
+ seen.accepts = append([]string(nil), h.seen.accepts...)
+ return seen
}
const homeEdgeBody = "served by the home edge"
@@ -720,6 +730,10 @@ func fakeHomeEdge(t *testing.T, h http.Handler) (*homeEdgeRecord, string) {
rec.seen.auth = r.Header.Get(hopAuthHeader)
rec.seen.xff = r.Header.Values("X-Forwarded-For")
rec.seen.proof = r.Header.Get(edgeproof.Header)
+ rec.seen.method = r.Method
+ rec.seen.fill = r.Header.Get(assetFillHeader)
+ rec.seen.header = r.Header.Clone()
+ rec.seen.accepts = append(rec.seen.accepts, r.Header.Get("Accept"))
rec.mu.Unlock()
h.ServeHTTP(w, r)
}))