carlos / platform Public

edge: local asset catch and fill, and the home side of a far fill (asset cache plan 3 Task 5)

serveAssetLocal answers a declared asset path on a route this box holds
from the disk store, or fills it from the app with an allow-listed
anonymous GET (fillFromApp): admitted at header time, written to a Fill
while hashed, abandoned at the 60 s deadline (reservation released then,
waiters forwarded), on a short body or a Set-Cookie trailer, committed
with a sha256 fallback ETag. A streamed initiator is teed and never
replayed onto; a HEAD, Range or conditional initiator is buffered and
answered from the entry. Hits pass the plan throttle; fills and uncached
fallbacks pass the rate limit. The policy's primary, owner and gen must
match the route snapshot's or the request is forwarded bypass.

serveAssetFillForHop answers a verified hop with a valid fill assertion
from the store or by filling, with the home's own expiry and a signed
acknowledgement, never touches the shared LRU, and leaves the request
unbilled (the observers still see it). responseModifier strips app-set
asset headers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 9f5d9916c6c6039d80bc107fe0d75c3a370f3b5b parent 25e4592
5 files changed, +1,783 −3
  • internal/edge/answered.go +4 −0
  • internal/edge/asset_local_test.go +1,019 −0
  • internal/edge/assetcatch.go +725 −0
  • internal/edge/cookiescope.go +5 −2
  • internal/edge/edge.go +30 −1
diff --git a/internal/edge/answered.go b/internal/edge/answered.go
index e92d52977..0518edcf4 100644
--- a/internal/edge/answered.go
+++ b/internal/edge/answered.go
@@ -39,6 +39,10 @@ type outcome struct {
// (MarkWoke), so a request record can say which request woke the app.
// Requests that queued behind the same wake are not marked.
woke bool
+ // unbilled is set on an acknowledged home fill (assetcatch.go,
+ // markUnbilled): the far edge meters what it delivers, so the observer
+ // defer skips the usage meter for it and only for it.
+ unbilled bool
}
// causeClientGone is the cause noted when a proxy fails because the CLIENT
diff --git a/internal/edge/asset_local_test.go b/internal/edge/asset_local_test.go
new file mode 100644
index 000000000..0317fc820
--- /dev/null
+++ b/internal/edge/asset_local_test.go
@@ -0,0 +1,1019 @@
+package edge
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "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 local catch and fill, and the home side of a far fill (edge asset cache
+// design §5.1 to §5.5, §8; plan 3 Task 5).
+//
+// Not acceptance: one Edge over a real registry, a real plan 2 store on a
+// temporary directory with a fake free-space source, and a fake LocalAssets
+// standing in for internal/host's policy snapshot. Task 9 is the two-edge
+// acceptance gate.
+
+const (
+ laHost = "shop.example.com"
+ laGen = "0123456789abcdef"
+ laBuild = "v1"
+ laBody = "console.log('shop');\n"
+)
+
+// bigFS is a free-space source with room for anything a test fills.
+type bigFS struct{}
+
+func (bigFS) Space(string) (total, free uint64, err error) { return 1 << 40, 1 << 39, nil }
+
+// fakeLocalAssets is LocalAssets as a settled policy snapshot answers it:
+// a fixed answer per host, and the builds that declare its paths.
+type fakeLocalAssets struct {
+ mu sync.Mutex
+ hosts map[string]HostAssets
+ builds map[string]bool
+}
+
+func (f *fakeLocalAssets) For(host string) (HostAssets, bool) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ a, ok := f.hosts[host]
+ return a, ok
+}
+
+func (f *fakeLocalAssets) Declared(host, build, path string) bool {
+ f.mu.Lock()
+ a, ok := f.hosts[host]
+ declares := f.builds[build]
+ f.mu.Unlock()
+ return ok && declares && assetPrefixMatch(a.Paths, path)
+}
+
+func (f *fakeLocalAssets) set(host string, a HostAssets) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.hosts[host] = a
+}
+
+func (f *fakeLocalAssets) declare(build string, ok bool) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.builds[build] = ok
+}
+
+func laAssets() HostAssets {
+ return HostAssets{Account: "abc", App: "shop", Paths: []string{"/assets/"}, Gen: laGen, At: time.Now(), Primary: laHost}
+}
+
+// laBackend is the app: it counts the requests it saw, keeps the last one's
+// headers, method and URI, and answers with handler (assetOK by default).
+type laBackend struct {
+ srv *httptest.Server
+ n atomic.Int64
+ mu sync.Mutex
+ last *http.Request
+ handler http.HandlerFunc
+}
+
+func (b *laBackend) lastReq() *http.Request {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.last
+}
+
+func newLABackend(t *testing.T, h http.HandlerFunc) *laBackend {
+ t.Helper()
+ b := &laBackend{handler: h}
+ b.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b.n.Add(1)
+ b.mu.Lock()
+ b.last = r.Clone(context.Background())
+ h := b.handler
+ b.mu.Unlock()
+ h(w, r)
+ }))
+ t.Cleanup(b.srv.Close)
+ return b
+}
+
+// assetOK answers body as a cacheable script, with extra headers.
+func assetOK(body string, extra ...string) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/javascript")
+ w.Header().Set("Cache-Control", "public, max-age=3600")
+ for i := 0; i+1 < len(extra); i += 2 {
+ w.Header().Set(extra[i], extra[i+1])
+ }
+ w.Header().Set("Content-Length", strconv.Itoa(len(body)))
+ io.WriteString(w, body)
+ }
+}
+
+type laScene struct {
+ e *Edge
+ reg *registry.Registry
+ b *laBackend
+ store *assetcache.Store
+ local *fakeLocalAssets
+}
+
+// newLAScene is one box serving laHost from one backend, armed with a real
+// store and a fake policy that catches /assets/ for build v1.
+func newLAScene(t *testing.T, h http.HandlerFunc, extra ...registry.Route) *laScene {
+ t.Helper()
+ b := newLABackend(t, h)
+ reg := openReg(t)
+ routes := append([]registry.Route{{Host: laHost, Kind: "instance", Addr: b.srv.Listener.Addr().String(),
+ Status: "ready", Account: "abc", App: "shop", AssetGen: laGen, Version: laBuild}}, extra...)
+ for _, rt := range routes {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatalf("upsert %s: %v", rt.Host, err)
+ }
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ t.Cleanup(e.probers.Stop)
+ e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))
+ s := &laScene{e: e, reg: reg, b: b, local: &fakeLocalAssets{hosts: map[string]HostAssets{}, builds: map[string]bool{}}}
+ s.local.set(laHost, laAssets())
+ s.local.declare(laBuild, true)
+ s.store = openLAStore(t)
+ e.assets = &assetState{store: s.store, local: s.local, now: time.Now}
+ return s
+}
+
+func openLAStore(t *testing.T) *assetcache.Store {
+ t.Helper()
+ st, err := assetcache.Open(assetcache.Config{Dir: filepath.Join(t.TempDir(), "asset-cache"), Budget: 1 << 30, FS: bigFS{}})
+ if err != nil {
+ t.Fatalf("open store: %v", err)
+ }
+ return st
+}
+
+func (s *laScene) do(t *testing.T, method, target string, hdr ...string) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(method, target, nil)
+ for i := 0; i+1 < len(hdr); i += 2 {
+ req.Header.Set(hdr[i], hdr[i+1])
+ }
+ rec := httptest.NewRecorder()
+ s.e.ServeHTTP(rec, req)
+ return rec
+}
+
+func (s *laScene) get(t *testing.T, path string, hdr ...string) *httptest.ResponseRecorder {
+ t.Helper()
+ return s.do(t, http.MethodGet, "http://"+laHost+path, hdr...)
+}
+
+func wantCache(t *testing.T, rec *httptest.ResponseRecorder, want string) {
+ t.Helper()
+ if got := rec.Header().Get("Carlos-Cache"); got != want {
+ t.Fatalf("Carlos-Cache = %q, want %q (status %d, body %q)", got, want, rec.Code, rec.Body.String())
+ }
+}
+
+func (s *laScene) key(path, rawQuery string) assetcache.Key {
+ a := laAssets()
+ return assetcache.Key{Account: a.Account, App: a.App, Gen: a.Gen, Host: laHost, Path: path, RawQuery: rawQuery}
+}
+
+func (s *laScene) lruLen() int {
+ s.e.cache.mu.Lock()
+ defer s.e.cache.mu.Unlock()
+ return len(s.e.cache.entries)
+}
+
+// waitFor polls cond for up to five seconds.
+func laWaitFor(t *testing.T, what string, cond func() bool) {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for !cond() {
+ if time.Now().After(deadline) {
+ t.Fatalf("timed out waiting for %s", what)
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+}
+
+func setFillDeadline(t *testing.T, d time.Duration) {
+ t.Helper()
+ old := assetFillDeadline
+ assetFillDeadline = d
+ t.Cleanup(func() { assetFillDeadline = old })
+}
+
+// ---- the local catch -----------------------------------------------------
+
+func TestLocalMissThenHit(t *testing.T) {
+ s := newLAScene(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())
+ }
+ 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 second.Header().Get("X-Carlos-Version") != "" {
+ t.Fatal("a hit carries X-Carlos-Version")
+ }
+ if n := s.b.n.Load(); n != 1 {
+ t.Fatalf("the backend saw %d requests, want 1", n)
+ }
+ if n := s.lruLen(); n != 0 {
+ t.Fatalf("the shared LRU holds %d entries for a caught path, want 0", n)
+ }
+}
+
+func TestLocalFillSendsNoCookieOrAuthorization(t *testing.T) {
+ s := newLAScene(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")
+ got := s.b.lastReq()
+ if got == nil {
+ t.Fatal("the backend saw nothing")
+ }
+ for _, h := range []string{"Cookie", "Authorization", "X-Custom"} {
+ if v := got.Header.Get(h); v != "" {
+ t.Errorf("the fill sent %s: %q", h, v)
+ }
+ }
+ if got.Header.Get("User-Agent") != "browser/1" || got.Header.Get("Accept") != "*/*" {
+ t.Errorf("the fill dropped an allowed header: %v", got.Header)
+ }
+ if ae := got.Header.Get("Accept-Encoding"); ae != "identity" {
+ t.Errorf("Accept-Encoding = %q, want identity", ae)
+ }
+ if got.Method != http.MethodGet || got.Host != laHost {
+ t.Errorf("fill = %s for host %q", got.Method, got.Host)
+ }
+}
+
+func TestLocalRefusedResponseServedNotStored(t *testing.T) {
+ big := strings.Repeat("x", assetcache.MaxBody+1)
+ cases := []struct {
+ name string
+ h http.HandlerFunc
+ code int
+ body string
+ }{
+ {"set-cookie", assetOK(laBody, "Set-Cookie", "a=b"), 200, laBody},
+ {"vary-cookie", assetOK(laBody, "Vary", "Cookie"), 200, laBody},
+ {"vary-origin", assetOK(laBody, "Vary", "Origin"), 200, laBody},
+ {"private", assetOK(laBody, "Cache-Control", "private, max-age=3600"), 200, laBody},
+ {"no-cache", assetOK(laBody, "Cache-Control", "no-cache"), 200, laBody},
+ {"206", 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("Content-Range", "bytes 0-3/10")
+ w.WriteHeader(206)
+ io.WriteString(w, "cons")
+ }, 206, "cons"},
+ {"404", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/plain")
+ w.Header().Set("Cache-Control", "public, max-age=3600")
+ w.WriteHeader(404)
+ io.WriteString(w, "gone")
+ }, 404, "gone"},
+ {"html-fallback", assetOK("<!doctype html>", "Content-Type", "text/html; charset=utf-8", "Cache-Control", "public, max-age=31536000"), 200, "<!doctype html>"},
+ {"oversized", assetOK(big), 200, big},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ s := newLAScene(t, c.h)
+ for i := 0; i < 2; i++ {
+ rec := s.get(t, "/assets/app.js")
+ wantCache(t, rec, "bypass")
+ if rec.Code != c.code || rec.Body.String() != c.body {
+ t.Fatalf("request %d = %d (%d bytes), want %d with the backend's body", i, rec.Code, rec.Body.Len(), c.code)
+ }
+ }
+ if st := s.store.Stats(); st.Entries != 0 || st.Reserved != 0 {
+ t.Fatalf("stats = %+v, want nothing stored or reserved", st)
+ }
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("the backend saw %d requests, want 2", n)
+ }
+ })
+ }
+}
+
+func TestLocalUndeclaringBuildIsNotStored(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody))
+ s.local.declare(laBuild, false)
+ wantCache(t, s.get(t, "/assets/app.js"), "bypass")
+ if st := s.store.Stats(); st.Entries != 0 {
+ t.Fatalf("an undeclaring build's answer was stored: %+v", st)
+ }
+}
+
+func TestHibernatingRouteHitDoesNotWake(t *testing.T) {
+ dir := genSockDir(t)
+ app := startGenApp(t, filepath.Join(dir, "a.sock"), assetOK(laBody))
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: laHost, Kind: "instance", Hibernate: true, Socket: filepath.Join(dir, "canon.sock"),
+ Status: "ready", Version: "v0", Account: "abc", App: "shop", AssetGen: laGen}); err != nil {
+ t.Fatal(err)
+ }
+ act := &genActivator{fakeGens: newFakeGens(true)}
+ act.switchTo(laHost, GenInfo{Socket: app.sock, N: 1, Build: laBuild})
+ e, err := New(reg, act)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ local := &fakeLocalAssets{hosts: map[string]HostAssets{laHost: laAssets()}, builds: map[string]bool{laBuild: true}}
+ store := openLAStore(t)
+ e.assets = &assetState{store: store, local: local, now: time.Now}
+
+ s := &laScene{e: e}
+ wantCache(t, s.get(t, "/assets/app.js"), "miss")
+ if act.served.Load() != 1 {
+ t.Fatalf("the fill reached the activator %d times, want 1", act.served.Load())
+ }
+ act.served.Store(0)
+ rec := s.get(t, "/assets/app.js")
+ wantCache(t, rec, "hit")
+ if rec.Body.String() != laBody {
+ t.Fatalf("hit body = %q", rec.Body.String())
+ }
+ if n := act.served.Load(); n != 0 {
+ t.Fatalf("a hit reached the activator %d times, want 0", n)
+ }
+}
+
+func TestHeadFillsWithGetAndAnswersHead(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody))
+ rec := s.do(t, http.MethodHead, "http://"+laHost+"/assets/app.js")
+ wantCache(t, rec, "miss")
+ if rec.Code != 200 || rec.Body.Len() != 0 {
+ t.Fatalf("HEAD = %d with %d body bytes", rec.Code, rec.Body.Len())
+ }
+ if got := s.b.lastReq().Method; got != http.MethodGet {
+ t.Fatalf("the fill was a %s, want GET", got)
+ }
+ hit := s.get(t, "/assets/app.js")
+ wantCache(t, hit, "hit")
+ if hit.Body.String() != laBody || s.b.n.Load() != 1 {
+ t.Fatalf("GET after HEAD = %q, backend saw %d", hit.Body.String(), s.b.n.Load())
+ }
+}
+
+func TestQueryIsPartOfTheKey(t *testing.T) {
+ s := newLAScene(t, func(w http.ResponseWriter, r *http.Request) {
+ assetOK("q="+r.URL.RawQuery)(w, r)
+ })
+ wantCache(t, s.get(t, "/assets/app.js?v=2"), "miss")
+ r3 := s.get(t, "/assets/app.js?v=3")
+ wantCache(t, r3, "miss")
+ r2 := s.get(t, "/assets/app.js?v=2")
+ wantCache(t, r2, "hit")
+ if r2.Body.String() != "q=v=2" || r3.Body.String() != "q=v=3" {
+ t.Fatalf("bodies %q %q", r2.Body.String(), r3.Body.String())
+ }
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("the backend saw %d requests, want 2", n)
+ }
+}
+
+// rawGet sends one GET over a fresh connection and returns everything the
+// edge wrote until it closed the connection.
+func rawGet(t *testing.T, addr, host, path string) []byte {
+ t.Helper()
+ b, err := rawGetErr(addr, host, path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+// rawGetErr is rawGet for a goroutine that may not call t.Fatal.
+func rawGetErr(addr, host, path string) ([]byte, error) {
+ c, err := net.Dial("tcp", addr)
+ if err != nil {
+ return nil, err
+ }
+ defer c.Close()
+ fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", path, host)
+ c.SetReadDeadline(time.Now().Add(10 * time.Second))
+ b, _ := io.ReadAll(c)
+ return b, nil
+}
+
+// wantOneResponse checks raw holds exactly one response, whose body is want.
+func wantOneResponse(t *testing.T, raw []byte, want string) {
+ t.Helper()
+ if n := bytes.Count(raw, []byte("HTTP/1.1 ")); n != 1 {
+ t.Fatalf("the client received %d status lines, want 1:\n%s", n, raw)
+ }
+ br := bufio.NewReader(bytes.NewReader(raw))
+ resp, err := http.ReadResponse(br, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatalf("body: %v", err)
+ }
+ if string(body) != want {
+ t.Fatalf("body = %q, want the upstream's %q", body, want)
+ }
+ if rest, _ := io.ReadAll(br); len(rest) != 0 {
+ t.Fatalf("%d bytes followed the response: %q", len(rest), rest)
+ }
+}
+
+func TestFillSurvivesTheInitiatorDisconnecting(t *testing.T) {
+ half := strings.Repeat("a", 4096)
+ cont := make(chan struct{})
+ s := newLAScene(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("Content-Length", strconv.Itoa(2*len(half)))
+ io.WriteString(w, half)
+ w.(http.Flusher).Flush()
+ <-cont
+ io.WriteString(w, half)
+ })
+ front := httptest.NewServer(s.e)
+ t.Cleanup(front.Close)
+ c, err := net.Dial("tcp", front.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ fmt.Fprintf(c, "GET /assets/app.js HTTP/1.1\r\nHost: %s\r\n\r\n", laHost)
+ if _, err := io.ReadFull(c, make([]byte, 64)); err != nil {
+ t.Fatalf("read the first bytes: %v", err)
+ }
+ c.Close()
+ close(cont)
+ laWaitFor(t, "the fill to commit", func() bool { return s.store.Stats().Entries == 1 })
+ rec := s.get(t, "/assets/app.js")
+ wantCache(t, rec, "hit")
+ if rec.Body.String() != half+half || s.b.n.Load() != 1 {
+ t.Fatalf("hit = %d bytes, backend saw %d", rec.Body.Len(), s.b.n.Load())
+ }
+}
+
+func TestShortBodyIsNotStored(t *testing.T) {
+ s := newLAScene(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("Content-Length", "100")
+ io.WriteString(w, strings.Repeat("s", 50))
+ })
+ s.get(t, "/assets/app.js")
+ if st := s.store.Stats(); st.Entries != 0 || st.Reserved != 0 {
+ t.Fatalf("a short body was kept: %+v", st)
+ }
+ s.get(t, "/assets/app.js")
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("the backend saw %d requests, want 2", n)
+ }
+}
+
+func TestColdMissAnswersARangeFromTheEntry(t *testing.T) {
+ s := newLAScene(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.b.lastReq().Header.Get("Range"); got != "" {
+ t.Fatalf("the fill forwarded Range %q", got)
+ }
+ wantCache(t, s.get(t, "/assets/app.js"), "hit")
+ if n := s.b.n.Load(); n != 1 {
+ t.Fatalf("the backend saw %d requests, want 1", n)
+ }
+}
+
+func TestColdMissAnswersIfNoneMatchFromTheEntry(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody, "ETag", `"e1"`))
+ rec := s.get(t, "/assets/app.js", "If-None-Match", `"e1"`)
+ wantCache(t, rec, "miss")
+ if rec.Code != http.StatusNotModified || rec.Body.Len() != 0 {
+ t.Fatalf("cold conditional = %d %q, want 304", rec.Code, rec.Body.String())
+ }
+ if got := s.b.lastReq().Header.Get("If-None-Match"); got != "" {
+ t.Fatalf("the fill forwarded If-None-Match %q", got)
+ }
+}
+
+func TestColdMissWithMultipleRangesGetsTheWholeBody(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody, "ETag", `"e1"`))
+ rec := s.get(t, "/assets/app.js", "Range", "bytes=0-1,4-5")
+ wantCache(t, rec, "miss")
+ if rec.Code != 200 || rec.Body.String() != laBody {
+ t.Fatalf("cold multi-range = %d %q, want 200 with the whole body", rec.Code, rec.Body.String())
+ }
+}
+
+func bodyETag(body string) string {
+ sum := sha256.Sum256([]byte(body))
+ return `"` + hex.EncodeToString(sum[:]) + `"`
+}
+
+func TestFallbackETagIsTheBodyHash(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody))
+ 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")
+ }
+ want := bodyETag(laBody)
+ if got := ent.Meta.Header.Get("ETag"); got != want {
+ t.Fatalf("stored ETag = %q, want %q", got, want)
+ }
+ rec := s.get(t, "/assets/app.js", "If-None-Match", want)
+ wantCache(t, rec, "hit")
+ if rec.Code != http.StatusNotModified {
+ t.Fatalf("conditional hit = %d, want 304", rec.Code)
+ }
+}
+
+func TestSetCookieTrailerVetoesTheFill(t *testing.T) {
+ for _, announced := range []bool{true, false} {
+ t.Run(fmt.Sprintf("announced=%v", announced), func(t *testing.T) {
+ s := newLAScene(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/javascript")
+ w.Header().Set("Cache-Control", "public, max-age=3600")
+ if announced {
+ w.Header().Set("Trailer", "Set-Cookie")
+ }
+ io.WriteString(w, laBody)
+ // Flushed, so the response is chunked: an unflushed small
+ // body gets a Content-Length and no trailer section at all.
+ w.(http.Flusher).Flush()
+ if announced {
+ w.Header().Set("Set-Cookie", "late=1")
+ } else {
+ w.Header().Set(http.TrailerPrefix+"Set-Cookie", "late=1")
+ }
+ })
+ s.get(t, "/assets/app.js")
+ s.get(t, "/assets/app.js")
+ if st := s.store.Stats(); st.Entries != 0 || st.Reserved != 0 {
+ t.Fatalf("a Set-Cookie trailer did not veto the fill: %+v", st)
+ }
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("the backend saw %d requests, want 2", n)
+ }
+ })
+ }
+}
+
+func TestStreamedInitiatorIsNotReplayedAfterATrailerVeto(t *testing.T) {
+ s := newLAScene(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("Trailer", "Set-Cookie")
+ io.WriteString(w, laBody)
+ w.Header().Set("Set-Cookie", "late=1")
+ })
+ front := httptest.NewServer(s.e)
+ t.Cleanup(front.Close)
+ wantOneResponse(t, rawGet(t, front.Listener.Addr().String(), laHost, "/assets/app.js"), laBody)
+ if st := s.store.Stats(); st.Entries != 0 {
+ t.Fatalf("stored after a veto: %+v", st)
+ }
+}
+
+func TestStreamedInitiatorIsNotReplayedAfterTheDeadline(t *testing.T) {
+ setFillDeadline(t, 100*time.Millisecond)
+ half := strings.Repeat("d", 2048)
+ s := newLAScene(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/javascript")
+ w.Header().Set("Cache-Control", "public, max-age=3600")
+ io.WriteString(w, half)
+ w.(http.Flusher).Flush()
+ time.Sleep(300 * time.Millisecond)
+ io.WriteString(w, half)
+ })
+ front := httptest.NewServer(s.e)
+ t.Cleanup(front.Close)
+ wantOneResponse(t, rawGet(t, front.Listener.Addr().String(), laHost, "/assets/app.js"), half+half)
+ if st := s.store.Stats(); st.Entries != 0 || st.Reserved != 0 {
+ t.Fatalf("stats after the deadline = %+v, want nothing", st)
+ }
+}
+
+func TestColdHeadIsBuffered(t *testing.T) {
+ t.Run("stored", func(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody))
+ rec := s.do(t, http.MethodHead, "http://"+laHost+"/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))
+ }
+ wantCache(t, s.get(t, "/assets/app.js"), "hit")
+ })
+ t.Run("refused", func(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody, "Cache-Control", "no-store"))
+ rec := s.do(t, http.MethodHead, "http://"+laHost+"/assets/app.js")
+ wantCache(t, rec, "bypass")
+ if rec.Code != 200 || rec.Body.Len() != 0 || rec.Header().Get("Cache-Control") != "no-store" {
+ t.Fatalf("refused HEAD = %d %d bytes %v", rec.Code, rec.Body.Len(), rec.Header())
+ }
+ })
+}
+
+func TestStalledFillIsAbandonedAtTheDeadline(t *testing.T) {
+ setFillDeadline(t, 200*time.Millisecond)
+ release := make(chan struct{})
+ started := make(chan struct{})
+ var first atomic.Bool
+ s := newLAScene(t, func(w http.ResponseWriter, r *http.Request) {
+ if first.CompareAndSwap(false, true) {
+ w.Header().Set("Content-Type", "application/javascript")
+ w.Header().Set("Cache-Control", "public, max-age=3600")
+ io.WriteString(w, "partial")
+ w.(http.Flusher).Flush()
+ close(started)
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ }
+ return
+ }
+ assetOK(laBody)(w, r)
+ })
+ front := httptest.NewServer(s.e)
+ t.Cleanup(front.Close)
+ t.Cleanup(func() {
+ select {
+ case <-release:
+ default:
+ close(release)
+ }
+ })
+ go rawGetErr(front.Listener.Addr().String(), laHost, "/assets/app.js")
+ <-started
+ laWaitFor(t, "the fill's reservation", func() bool { return s.store.Stats().Reserved > 0 })
+
+ waiter := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ req := httptest.NewRequest(http.MethodGet, "http://"+laHost+"/assets/app.js", nil)
+ rec := httptest.NewRecorder()
+ s.e.ServeHTTP(rec, req)
+ waiter <- rec
+ }()
+
+ laWaitFor(t, "the reservation's release at the deadline", func() bool { return s.store.Stats().Reserved == 0 })
+ select {
+ case rec := <-waiter:
+ wantCache(t, rec, "bypass")
+ if rec.Body.String() != laBody {
+ t.Fatalf("waiter body = %q", rec.Body.String())
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("the waiter was not forwarded at the deadline")
+ }
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("the backend saw %d requests, want 2 (the stalled fill and the forwarded waiter)", n)
+ }
+ if st := s.store.Stats(); st.Entries != 0 {
+ t.Fatalf("an abandoned fill stored %+v", st)
+ }
+}
+
+func TestNonCanonicalPathBypasses(t *testing.T) {
+ for _, p := range []string{"/assets//app.js", "/assets/./app.js", "/assets/%61pp.js"} {
+ t.Run(p, func(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody))
+ rec := s.get(t, p, "Cookie", "a=b")
+ wantCache(t, rec, "bypass")
+ got := s.b.lastReq()
+ if got.RequestURI != p {
+ t.Fatalf("the backend saw %q, want the original %q", got.RequestURI, p)
+ }
+ if got.Header.Get("Cookie") != "a=b" {
+ t.Fatal("a bypass dropped the client's headers")
+ }
+ if st := s.store.Stats(); st.Entries != 0 {
+ t.Fatalf("a non-canonical path was stored: %+v", st)
+ }
+ })
+ }
+}
+
+func TestPostUnderAPrefixPassesThrough(t *testing.T) {
+ s := newLAScene(t, func(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ w.Header().Set("Content-Type", "text/plain")
+ fmt.Fprintf(w, "%s %s %s", r.Method, r.Header.Get("Cookie"), b)
+ })
+ req := httptest.NewRequest(http.MethodPost, "http://"+laHost+"/assets/upload", strings.NewReader("payload"))
+ req.Header.Set("Cookie", "a=b")
+ rec := httptest.NewRecorder()
+ s.e.ServeHTTP(rec, req)
+ if rec.Body.String() != "POST a=b payload" {
+ t.Fatalf("POST = %q", rec.Body.String())
+ }
+ if got := rec.Header().Get("Carlos-Cache"); got != "" {
+ t.Fatalf("a POST was answered Carlos-Cache %q", got)
+ }
+}
+
+// TestPolicyAndSnapshotDisagreeingFillsNothing: the policy's settled
+// snapshot has moved an alias to another app while the edge's route
+// snapshot (Edge.Reload, withheld here) still serves it with the old
+// primary. Nothing is filled or acknowledged until both agree.
+func TestPolicyAndSnapshotDisagreeingFillsNothing(t *testing.T) {
+ blog := newLABackend(t, assetOK("blog"))
+ s := newLAScene(t, assetOK(laBody), registry.Route{Host: "blog.example.com", Kind: "instance",
+ Addr: blog.srv.Listener.Addr().String(), Status: "ready", Account: "abc", App: "blog", AssetGen: "fedcba9876543210", Version: laBuild})
+ const alias = "www.example.com"
+ if err := s.reg.UpsertAlias(registry.RouteAlias{Alias: alias, Host: laHost, Account: "abc", App: "shop"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ // The registry and the policy move the alias to blog; Reload is withheld.
+ if err := s.reg.UpsertAlias(registry.RouteAlias{Alias: alias, Host: "blog.example.com", Account: "abc", App: "blog"}); err != nil {
+ t.Fatal(err)
+ }
+ moved := HostAssets{Account: "abc", App: "blog", Paths: []string{"/assets/"}, Gen: "fedcba9876543210", At: time.Now(), Primary: "blog.example.com"}
+ s.local.set(alias, moved)
+
+ rec := s.do(t, http.MethodGet, "http://"+alias+"/assets/app.js")
+ wantCache(t, rec, "bypass")
+ if rec.Body.String() != laBody {
+ t.Fatalf("body = %q, want the snapshot's route's answer, uncached", rec.Body.String())
+ }
+ if st := s.store.Stats(); st.Entries != 0 {
+ t.Fatalf("a disagreeing pair filled %+v", st)
+ }
+
+ key := s.armMesh(t)
+ resp := s.hop(t, key, alias, "/assets/app.js", assetFillClaims{Host: alias, PathQuery: "/assets/app.js", Account: "abc", App: "blog", Gen: moved.Gen})
+ if resp.Header().Get(assetAckHeader) != "" || resp.Header().Get(assetExpiresHeader) != "" {
+ t.Fatalf("a far fill was acknowledged while the snapshots disagree: %v", resp.Header())
+ }
+ if st := s.store.Stats(); st.Entries != 0 {
+ t.Fatalf("a disagreeing far fill stored %+v", st)
+ }
+}
+
+// ---- the home side of a far fill ------------------------------------------
+
+// armMesh gives the scene's edge a mirrored mesh key, as a home box has.
+func (s *laScene) armMesh(t *testing.T) []byte {
+ t.Helper()
+ ms := meshTestStore(t)
+ if err := mintMeshKey(context.Background(), ms); err != nil {
+ t.Fatal(err)
+ }
+ m := newHomeMap(ms, "annie")
+ refreshHomeMap(t, m)
+ s.e.homes.Store(m)
+ key, _ := m.meshKeys()
+ if len(key) == 0 {
+ t.Fatal("no mesh key mirrored")
+ }
+ return key
+}
+
+// hop sends what a far edge's fill sends: a verified hop, the allow-listed
+// headers, and an assertion of c (none when c is the zero value).
+func (s *laScene) hop(t *testing.T, key []byte, host, path string, c assetFillClaims) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodGet, "http://"+host+path, nil)
+ now := time.Now()
+ req.Header.Set(hopHeader, "1")
+ req.Header.Set(hopAuthHeader, signHop(key, host, now))
+ req.Header.Set("X-Forwarded-For", "203.0.113.7")
+ req.Header.Set("Accept-Encoding", "identity")
+ if c != (assetFillClaims{}) {
+ req.Header.Set(assetFillHeader, signAssetFill(key, c, now))
+ }
+ rec := httptest.NewRecorder()
+ s.e.ServeHTTP(rec, req)
+ return rec
+}
+
+func laClaims(path string) assetFillClaims {
+ return assetFillClaims{Host: laHost, PathQuery: path, Account: "abc", App: "shop", Gen: laGen}
+}
+
+// homeFill sends one fill and checks its acknowledgement verifies; it
+// returns the response and the expiry it acknowledged.
+func (s *laScene) homeFill(t *testing.T, key []byte, path string) (*httptest.ResponseRecorder, int64) {
+ t.Helper()
+ now := time.Now()
+ c := laClaims(path)
+ assertion := signAssetFill(key, c, now)
+ req := httptest.NewRequest(http.MethodGet, "http://"+laHost+path, nil)
+ req.Header.Set(hopHeader, "1")
+ req.Header.Set(hopAuthHeader, signHop(key, laHost, now))
+ req.Header.Set("X-Forwarded-For", "203.0.113.7")
+ req.Header.Set("Accept-Encoding", "identity")
+ req.Header.Set(assetFillHeader, assertion)
+ rec := httptest.NewRecorder()
+ s.e.ServeHTTP(rec, req)
+ expHdr := rec.Header().Get(assetExpiresHeader)
+ exp, err := strconv.ParseInt(expHdr, 10, 64)
+ if err != nil {
+ t.Fatalf("X-Carlos-Asset-Expires = %q: %v (headers %v)", expHdr, err, rec.Header())
+ }
+ if !verifyAssetAck(key, assertion, exp, rec.Header().Get(assetAckHeader)) {
+ t.Fatalf("the acknowledgement %q does not verify for expiry %d", rec.Header().Get(assetAckHeader), exp)
+ }
+ return rec, exp
+}
+
+func TestHomeFillAcknowledgesAndSkipsTheMeter(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody))
+ key := s.armMesh(t)
+ m := NewUsageMeter()
+ s.e.EnableUsage(m)
+
+ rec, exp := s.homeFill(t, key, "/assets/app.js")
+ if rec.Code != 200 || rec.Body.String() != laBody {
+ t.Fatalf("fill = %d %q", rec.Code, rec.Body.String())
+ }
+ ent, ok := s.store.Get(s.key("/assets/app.js", ""))
+ if !ok {
+ t.Fatal("the home stored nothing")
+ }
+ if exp == 0 || exp != ent.Meta.Expires.Unix() {
+ t.Fatalf("acknowledged expiry %d, want the entry's %d", exp, ent.Meta.Expires.Unix())
+ }
+ if got := s.b.lastReq().Header.Get(assetFillHeader); got != "" {
+ t.Fatalf("the assertion reached the app: %q", got)
+ }
+ hit, hitExp := s.homeFill(t, key, "/assets/app.js")
+ wantCache(t, hit, "hit")
+ if hitExp != exp || hit.Body.String() != laBody || s.b.n.Load() != 1 {
+ t.Fatalf("home hit = %q expiry %d, backend saw %d", hit.Body.String(), hitExp, s.b.n.Load())
+ }
+ if row, ok := m.Drain()[laHost]; ok && (row.Requests != 0 || row.BytesOut != 0) {
+ t.Fatalf("the home metered an acknowledged fill: %+v", row)
+ }
+ if n := s.lruLen(); n != 0 {
+ t.Fatalf("the shared LRU holds %d entries, want 0", n)
+ }
+}
+
+func wantMeteredHop(t *testing.T, m *UsageMeter) {
+ t.Helper()
+ row := m.Drain()[laHost]
+ if row.Requests != 1 || row.HopRequests != 1 {
+ t.Fatalf("row = %+v, want one metered hop", row)
+ }
+}
+
+func TestHomeFillWithStaleGenGetsNoAck(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody))
+ key := s.armMesh(t)
+ m := NewUsageMeter()
+ s.e.EnableUsage(m)
+ c := laClaims("/assets/app.js")
+ c.Gen = "1111111111111111"
+ rec := s.hop(t, key, laHost, "/assets/app.js", c)
+ if rec.Header().Get(assetAckHeader) != "" || rec.Header().Get(assetExpiresHeader) != "" {
+ t.Fatalf("a stale-generation fill was acknowledged: %v", rec.Header())
+ }
+ wantMeteredHop(t, m)
+}
+
+func TestHomeFillWithChangedOwnerGetsNoAck(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody))
+ key := s.armMesh(t)
+ m := NewUsageMeter()
+ s.e.EnableUsage(m)
+ c := laClaims("/assets/app.js")
+ c.App = "blog"
+ rec := s.hop(t, key, laHost, "/assets/app.js", c)
+ if rec.Header().Get(assetAckHeader) != "" {
+ t.Fatalf("a fill for another owner was acknowledged: %v", rec.Header())
+ }
+ wantMeteredHop(t, m)
+}
+
+func TestHomeFillUncacheableIsAcknowledgedWithZeroExpiry(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody, "Cache-Control", "no-store"))
+ key := s.armMesh(t)
+ m := NewUsageMeter()
+ s.e.EnableUsage(m)
+ rec, exp := s.homeFill(t, key, "/assets/app.js")
+ if exp != 0 || rec.Body.String() != laBody {
+ t.Fatalf("uncacheable fill = %q expiry %d, want the body with expiry 0", rec.Body.String(), exp)
+ }
+ if st := s.store.Stats(); st.Entries != 0 {
+ t.Fatalf("stored %+v", st)
+ }
+ if row, ok := m.Drain()[laHost]; ok && row.Requests != 0 {
+ t.Fatalf("the home metered an acknowledged fill: %+v", row)
+ }
+}
+
+func TestAppSetAckHeadersAreStripped(t *testing.T) {
+ s := newLAScene(t, func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set(assetAckHeader, "forged")
+ w.Header().Set(assetExpiresHeader, "4102444800")
+ w.Header().Set("Carlos-Cache", "forged")
+ assetOK(laBody)(w, r)
+ })
+ key := s.armMesh(t)
+ rec, exp := s.homeFill(t, key, "/assets/app.js")
+ ent, ok := s.store.Get(s.key("/assets/app.js", ""))
+ if !ok || exp != ent.Meta.Expires.Unix() {
+ t.Fatalf("expiry %d, want the home's own %v", exp, ent)
+ }
+ if got := rec.Header().Values(assetAckHeader); len(got) != 1 {
+ t.Fatalf("ack values %q, want only the home's", got)
+ }
+ plain := s.get(t, "/index.html")
+ for _, h := range []string{assetAckHeader, assetExpiresHeader, "Carlos-Cache"} {
+ if v := plain.Header().Get(h); v != "" {
+ t.Errorf("a plain response carried the app's %s: %q", h, v)
+ }
+ }
+}
+
+// ---- admission around the catch (drift D7, D8) -----------------------------
+
+// Fills and uncached fallbacks go through the per-instance rate limit; hits
+// stay exempt (D7).
+func TestAssetFillsAreRateLimitedAndHitsAreNot(t *testing.T) {
+ t.Setenv("CARLOS_RATE_LIMIT", "enforce")
+ s := newLAScene(t, assetOK(laBody))
+ if err := s.reg.Upsert(registry.Route{Host: laHost, Kind: "instance", Addr: s.b.srv.Listener.Addr().String(),
+ Status: "ready", Account: "abc", App: "shop", AssetGen: laGen, Version: laBuild, RateLimit: `{"rate":1,"burst":2}`}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ wantCache(t, s.get(t, "/assets/a.js"), "miss")
+ wantCache(t, s.get(t, "/assets/b.js"), "miss")
+ for i := 0; i < 10; i++ {
+ wantCache(t, s.get(t, "/assets/a.js"), "hit")
+ }
+ if rec := s.get(t, "/assets/c.js"); rec.Code != http.StatusTooManyRequests {
+ t.Fatalf("a third fill past the burst = %d, want 429", rec.Code)
+ }
+}
+
+// Caught deliveries, hits included, pass the account throttle and its
+// refusal metering (D8).
+func TestAssetHitsPassThePlanThrottle(t *testing.T) {
+ s := newLAScene(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" {
+ return plans.Throttle{}, false
+ }
+ return plans.Throttle{Bandwidth: true, Until: frozen.Add(time.Hour)}, true
+ })
+ m := NewUsageMeter()
+ s.e.EnableUsage(m)
+ wantCache(t, s.get(t, "/assets/app.js"), "miss")
+ 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 hits refused past the throttle's burst, want 1", refused)
+ }
+ if row := m.Drain()[laHost]; row.PlanThrottled != 1 {
+ t.Fatalf("row = %+v, want one plan-throttle refusal metered", row)
+ }
+}
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go
index 9a3b1573a..d085bf544 100644
--- a/internal/edge/assetcatch.go
+++ b/internal/edge/assetcatch.go
@@ -2,13 +2,22 @@ package edge
import (
"context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "hash"
+ "net/http"
"net/url"
"path"
+ "strconv"
"strings"
"sync"
"time"
"github.com/carlosframework/platform/internal/assetcache"
+ "github.com/carlosframework/platform/internal/geoip"
+ "github.com/carlosframework/platform/internal/release"
)
// The catch decision, the cache key and the fill coalescer (edge asset cache
@@ -149,3 +158,719 @@ func (f *assetFlight) join(id string) (leader bool, wait func(ctx context.Contex
}
}, noDone
}
+
+// ---- serving on a box that holds the route (§5.1 to §5.5, §8) --------------
+
+// assetState is a box's armed asset cache: the store, the home's own catch
+// (internal/host's settled policy snapshot, plan 3 drift D3), the fill
+// coalescer, and the clock admission and Age are judged by. Nil on Edge
+// means unarmed: every hook below is then one nil check.
+type assetState struct {
+ store *assetcache.Store
+ local LocalAssets
+ flight assetFlight
+ now func() time.Time
+}
+
+func (s *assetState) clock() time.Time {
+ if s.now != nil {
+ return s.now()
+ }
+ return time.Now()
+}
+
+// assetFillDeadline is how long a fill may take from its start to the last
+// body byte (§5.3). A variable only so a test can shorten it.
+var assetFillDeadline = 60 * time.Second
+
+var (
+ // errAssetUndelivered: the fill wrote nothing to the initiator, which is
+ // still owed an answer (a buffered initiator whose fill was abandoned
+ // after the headers, or a fill that never got headers at all).
+ errAssetUndelivered = errors.New("edge: asset fill delivered nothing to the initiator")
+ // errAssetNotStored: the initiator was answered with the response as it
+ // came, and nothing was stored.
+ errAssetNotStored = errors.New("edge: asset fill stored nothing")
+ // errAssetBrokeOff: the upstream's body broke off while it was being
+ // streamed to the initiator, which must then see the break, as an
+ // uncached response's client would.
+ errAssetBrokeOff = errors.New("edge: asset fill's upstream broke off mid-body")
+)
+
+// assetBuffered reports whether an initiating request waits for the commit
+// and is answered from the entry (astra P3-5) rather than being teed the
+// body as it fills: a HEAD, or a request with a Range or a validator, whose
+// answer the entry has to compute.
+func assetBuffered(r *http.Request) bool {
+ if r.Method == http.MethodHead {
+ return true
+ }
+ for _, h := range []string{"Range", "If-None-Match", "If-Modified-Since", "If-Range"} {
+ if _, ok := r.Header[h]; ok {
+ return true
+ }
+ }
+ return false
+}
+
+// assetPathQuery is the path and raw query an assertion signs
+// (assetFillClaims.PathQuery): the request URI as sent, which for a
+// canonical path is the path, then "?" and the raw query when there is one.
+// The far edge signs with the same function.
+func assetPathQuery(u *url.URL) string { return u.RequestURI() }
+
+// assetUpstreamMatches is the upstream rule (astra P4-2, drift D4): the
+// policy's decision for a host and the route the edge's own snapshot serves
+// it with must name the same primary route, owner and generation. The two
+// snapshots reload on their own schedules, so for a moment after an alias
+// changes owner they can disagree; a request in that moment is an ordinary
+// uncached one, and a far fill gets no acknowledgement.
+func assetUpstreamMatches(a HostAssets, up upstream) bool {
+ return a.Primary != "" && a.Primary == up.route.Host &&
+ a.Account == release.RouteAccount(up.route) && a.App == up.route.App &&
+ a.Gen != "" && a.Gen == up.route.AssetGen
+}
+
+// localAssetCatch is the catch decision on a box with a local route row
+// (§5.1): armed, GET or HEAD, a route the policy could catch for at all,
+// and a path under a prefix the policy's snapshot holds for host. The
+// canonical-path and upstream checks come later: a request that fails them
+// is still under a prefix, and is answered bypass.
+func (e *Edge) localAssetCatch(r *http.Request, host string, up upstream) (HostAssets, bool) {
+ st := e.assets
+ if st == nil || st.store == nil || st.local == nil {
+ return HostAssets{}, false
+ }
+ if r.Method != http.MethodGet && r.Method != http.MethodHead {
+ return HostAssets{}, false
+ }
+ // The policy refuses these routes outright; the route snapshot is
+ // checked too, so a policy that lags a gate or an import never serves a
+ // stored body past it.
+ if up.route.Kind == "status" || up.route.Gate != "" || up.route.ImportGate != "" {
+ return HostAssets{}, false
+ }
+ a, ok := st.local.For(host)
+ if !ok || !assetPrefixMatch(a.Paths, r.URL.Path) {
+ return HostAssets{}, false
+ }
+ return a, true
+}
+
+// serveAssetLocal is the local catch (§5.1), called after the upgrade branch
+// and before the gzip wrapper and the shared cache, so caught responses
+// write their own representation and never read or fill the shared LRU. It
+// reports whether it answered; false leaves the request to the ordinary
+// path exactly as before.
+//
+// Every caught delivery, a hit included, first passes the account throttle
+// with its refusal metering (drift D8), here rather than at the ordinary
+// call so that an uncaught request is judged exactly once. Every upstream
+// fill and uncached fallback then passes the per-instance rate limit, which
+// still never limits a hit (D7).
+func (e *Edge) serveAssetLocal(w http.ResponseWriter, r *http.Request, host string, up upstream) bool {
+ a, ok := e.localAssetCatch(r, host, up)
+ if !ok {
+ return false
+ }
+ if !e.planThrottleAdmit(w, r, up) {
+ return true
+ }
+ if !canonicalAssetPath(r.URL) || !assetUpstreamMatches(a, up) {
+ e.assetForward(w, r, up, nil)
+ return true
+ }
+ st := e.assets
+ k := assetKey(a, host, r.URL)
+ if ent, ok := st.store.Get(k); ok && serveAssetEntry(w, r, ent, st.clock(), "hit") == nil {
+ return true
+ }
+ leader, wait, done := st.flight.join(k.ID())
+ if !leader {
+ if ent, ok := wait(r.Context()); ok && serveAssetEntry(w, r, ent, st.clock(), "hit") == nil {
+ return true
+ }
+ e.assetForward(w, r, up, nil)
+ return true
+ }
+ release, admitted := e.rateAdmit(w, r, up)
+ if !admitted {
+ done(nil)
+ return true
+ }
+ e.leadAssetFill(w, r, up, k, a, release, done, nil, nil)
+ return true
+}
+
+// serveAssetFillForHop is the home side of a far edge's fill (§5.3). It
+// handles a verified hop carrying X-Carlos-Asset-Fill when the assertion
+// verifies for the owner and generation this box's policy holds for host,
+// the policy catches the path, and the upstream rule holds; on any failure
+// it returns false and the request continues as an ordinary hop, metered
+// as one, with no acknowledgement. The assertion is deleted from the
+// request either way, so the app never sees it.
+//
+// A handled fill is answered from the store, or filled from the app,
+// never from or into the shared LRU. Its response carries the home's own
+// X-Carlos-Asset-Expires (the entry's expiry, or 0 when the response is not
+// storable) and X-Carlos-Asset-Fill-Ack, signed with the key the assertion
+// verified under; the app's own values of both are deleted first. The
+// request is marked unbilled: the far edge meters what it delivers. Only
+// billing is skipped (drift D9); the other observers see the response.
+//
+// A far fill is a plain GET (Task 6 sends nothing else); any other shape is
+// an ordinary hop.
+func (e *Edge) serveAssetFillForHop(w http.ResponseWriter, r *http.Request, host string, up upstream) bool {
+ assertion := r.Header.Get(assetFillHeader)
+ if assertion == "" {
+ return false
+ }
+ r.Header.Del(assetFillHeader)
+ if !hopVerified(r.Context()) || r.Method != http.MethodGet || assetBuffered(r) || isUpgradeRequest(r) {
+ return false
+ }
+ a, ok := e.localAssetCatch(r, host, up)
+ if !ok || !canonicalAssetPath(r.URL) || !assetUpstreamMatches(a, up) {
+ return false
+ }
+ current, next := e.homes.Load().meshKeys()
+ key, ok := verifyAssetFill(current, next, assetFillClaims{
+ Host: host, PathQuery: assetPathQuery(r.URL), Account: a.Account, App: a.App, Gen: a.Gen,
+ }, assertion, time.Now())
+ if !ok {
+ return false
+ }
+ markUnbilled(r)
+ ack := func(h http.Header, expires int64) {
+ h.Del(assetAckHeader)
+ h.Del(assetExpiresHeader)
+ h.Set(assetExpiresHeader, strconv.FormatInt(expires, 10))
+ h.Set(assetAckHeader, signAssetAck(key, assertion, expires))
+ }
+ unack := func(h http.Header) {
+ h.Del(assetAckHeader)
+ h.Del(assetExpiresHeader)
+ }
+ st := e.assets
+ k := assetKey(a, host, r.URL)
+ serveHit := func(ent *assetcache.Entry) bool {
+ ack(w.Header(), ent.Meta.Expires.Unix())
+ if serveAssetEntry(w, r, ent, st.clock(), "hit") == nil {
+ return true
+ }
+ unack(w.Header())
+ return false
+ }
+ if ent, ok := st.store.Get(k); ok && serveHit(ent) {
+ return true
+ }
+ unstorable := func(h http.Header) { ack(h, 0) }
+ leader, wait, done := st.flight.join(k.ID())
+ if !leader {
+ if ent, ok := wait(r.Context()); ok && serveHit(ent) {
+ return true
+ }
+ e.assetForward(w, r, up, unstorable)
+ return true
+ }
+ // A rate-limit refusal is this home's answer to the fill, so it is
+ // acknowledged as unstorable and the far edge meters it.
+ unstorable(w.Header())
+ release, admitted := e.rateAdmit(w, r, up)
+ if !admitted {
+ done(nil)
+ return true
+ }
+ unack(w.Header())
+ e.leadAssetFill(w, r, up, k, a, release, done, func(v assetVerdict, h http.Header) {
+ var exp int64
+ if v.Store {
+ exp = v.Expires.Unix()
+ }
+ ack(h, exp)
+ }, unstorable)
+ return true
+}
+
+// markUnbilled marks r's outcome so ServeHTTP's observer defer skips the
+// usage meter for it, and nothing else.
+func markUnbilled(r *http.Request) {
+ if o, ok := r.Context().Value(answeredKey{}).(*outcome); ok {
+ o.unbilled = true
+ }
+}
+
+// assetForward is the uncached fallback: the request forwarded exactly as
+// today, through the rate limit (D7), answered Carlos-Cache: bypass. onHeader,
+// when set, edits the response headers at the first final status.
+func (e *Edge) assetForward(w http.ResponseWriter, r *http.Request, up upstream, onHeader func(http.Header)) {
+ release, ok := e.rateAdmit(w, r, up)
+ if !ok {
+ return
+ }
+ if release != nil {
+ defer release()
+ w = &slotWriter{ResponseWriter: w, release: release}
+ }
+ w = &assetResultWriter{ResponseWriter: w, result: "bypass", onHeader: onHeader}
+ if up.hibernating && e.act.ServeHTTP(w, r, up.route, up.proxy) {
+ return
+ }
+ up.proxy.ServeHTTP(w, r)
+}
+
+// assetResultWriter sets Carlos-Cache at the first final status, after the
+// proxy has copied the upstream's headers in (and after any 1xx block, which
+// the proxy clears the header map behind).
+type assetResultWriter struct {
+ http.ResponseWriter
+ result string
+ onHeader func(http.Header)
+ wrote bool
+}
+
+func (a *assetResultWriter) WriteHeader(code int) {
+ if code >= 200 && !a.wrote {
+ a.wrote = true
+ h := a.Header()
+ h.Set(assetCacheHeader, a.result)
+ if a.onHeader != nil {
+ a.onHeader(h)
+ }
+ }
+ a.ResponseWriter.WriteHeader(code)
+}
+
+func (a *assetResultWriter) Write(p []byte) (int, error) {
+ if !a.wrote {
+ a.WriteHeader(http.StatusOK)
+ }
+ return a.ResponseWriter.Write(p)
+}
+
+func (a *assetResultWriter) Flush() {
+ if !a.wrote {
+ a.WriteHeader(http.StatusOK)
+ }
+ _ = http.NewResponseController(a.ResponseWriter).Flush()
+}
+
+func (a *assetResultWriter) Unwrap() http.ResponseWriter { return a.ResponseWriter }
+
+// 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
+// it back on the ordinary path. done settles the flight: at once when the
+// 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.
+//
+// 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)) {
+ defer done(nil)
+ if release != nil {
+ defer release()
+ }
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), assetFillDeadline)
+ 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) {
+ if release != nil {
+ release()
+ }
+ if !v.Store {
+ done(nil)
+ }
+ if onHeader != nil {
+ onHeader(v, h)
+ }
+ })
+ stop()
+ done(ent)
+ switch {
+ case ent != nil && assetBuffered(r):
+ if serveAssetEntry(w, r, ent, e.assets.clock(), "miss") == nil {
+ return
+ }
+ e.assetForward(w, r, up, onForward)
+ case ent == nil && errors.Is(err, errAssetUndelivered):
+ e.assetForward(w, r, up, onForward)
+ 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.
+ if r.Context().Value(http.ServerContextKey) != nil {
+ panic(http.ErrAbortHandler)
+ }
+ }
+}
+
+// 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
+// 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.
+//
+// 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
+// stored and bypass when not; a buffered one gets nothing while the fill is
+// storing, and the response as it came (bypass) when the verdict or the
+// reservation refuses at header time, headers only for a HEAD.
+//
+// The fill is abandoned (its reservation released at that moment) when ctx
+// ends, which is the caller's 60 s deadline, and after the body on a short
+// body or a Set-Cookie trailer. Abandoning stops only the caching: a teed
+// initiator keeps receiving the upstream's bytes to the end, and nothing is
+// replayed onto it. The upstream request outlives the initiator while the
+// fill is storing, so a client that disconnects does not cost the waiters
+// 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
+// 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) {
+ 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,
+ buffered: assetBuffered(r), head: r.Method == http.MethodHead,
+ onHeader: onHeader, cancelUp: upCancel,
+ hdr: http.Header{}, hash: sha256.New(), cl: -1, reqTime: st.clock(),
+ }
+ stopDeadline := context.AfterFunc(ctx, fw.abandon)
+ defer stopDeadline()
+ stopClient := context.AfterFunc(r.Context(), fw.clientLeft)
+ defer stopClient()
+ brokeOff := fw.dispatch(assetFillRequest(upCtx, r))
+ return fw.finish(brokeOff)
+}
+
+// assetFillRequest is the allow-listed upstream request for a fill of r.
+func assetFillRequest(ctx context.Context, r *http.Request) *http.Request {
+ u := *r.URL
+ u.User = nil
+ u.Fragment, u.RawFragment = "", ""
+ req := &http.Request{
+ Method: http.MethodGet,
+ URL: &u,
+ Proto: "HTTP/1.1",
+ ProtoMajor: 1,
+ ProtoMinor: 1,
+ Header: http.Header{},
+ Body: http.NoBody,
+ Host: r.Host,
+ RemoteAddr: r.RemoteAddr,
+ RequestURI: u.RequestURI(),
+ TLS: r.TLS,
+ }
+ for _, name := range []string{"User-Agent", "Accept"} {
+ if vs := r.Header.Values(name); len(vs) > 0 {
+ req.Header[name] = append([]string(nil), vs...)
+ }
+ }
+ req.Header.Set("Accept-Encoding", "identity")
+ return req.WithContext(ctx)
+}
+
+// assetFillWriter is the ResponseWriter a fill's upstream writes into. The
+// handler runs on the request's own goroutine; abandon and clientLeft run
+// on context callbacks, so the state they share is under mu.
+type assetFillWriter struct {
+ e *Edge
+ st *assetState
+ w http.ResponseWriter // the initiator's writer
+ r *http.Request // the initiating request
+ up upstream
+ k assetcache.Key
+ a HostAssets
+ buffered bool
+ head bool
+ onHeader func(assetVerdict, http.Header)
+ cancelUp context.CancelFunc
+ reqTime time.Time
+
+ hdr http.Header // what the upstream handler writes into
+ wrote bool
+ snap http.Header // hdr as of the final status
+ verdict assetVerdict
+ cl int64 // the declared Content-Length, -1 when none
+ n int64 // body bytes received
+ hash hash.Hash
+
+ mu sync.Mutex
+ fill *assetcache.Fill // nil when not storing (refused, abandoned, done)
+ headerDone bool
+ tee bool // the initiator is being written the response
+ abandoned bool // the deadline came
+ clientGone bool
+ cancelled bool // the upstream was cancelled because nobody needed it
+}
+
+func (fw *assetFillWriter) Header() http.Header { return fw.hdr }
+
+// dispatch sends req upstream, reporting whether the handler broke off the
+// body (httputil.ReverseProxy's ErrAbortHandler).
+func (fw *assetFillWriter) dispatch(req *http.Request) (brokeOff bool) {
+ defer func() {
+ if p := recover(); p != nil {
+ if p != http.ErrAbortHandler {
+ panic(p)
+ }
+ 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)
+ return false
+}
+
+func (fw *assetFillWriter) WriteHeader(code int) {
+ // 1xx blocks are not forwarded: the initiator may be buffered, and a
+ // stored entry has none to replay.
+ if code < 200 || fw.wrote {
+ return
+ }
+ 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)
+ 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 {
+ fw.cl = n
+ }
+ }
+ var fill *assetcache.Fill
+ if v.Store {
+ if f, err := fw.st.store.Reserve(fw.k, fw.cl); err == nil {
+ fill = f
+ }
+ }
+ fw.mu.Lock()
+ if fill != nil && fw.abandoned {
+ fill.Abort()
+ fill = nil
+ }
+ fw.fill = fill
+ fw.tee = !fw.buffered || fill == nil
+ fw.headerDone = true
+ tee := fw.tee
+ fw.mu.Unlock()
+
+ out := http.Header{}
+ if tee {
+ out = fw.w.Header()
+ }
+ for k, vs := range fw.snap {
+ out[k] = append([]string(nil), vs...)
+ }
+ result := "bypass"
+ if fill != nil {
+ result = "miss"
+ }
+ out.Set(assetCacheHeader, result)
+ if fw.onHeader != nil {
+ fw.onHeader(v, out)
+ }
+ if tee {
+ fw.w.WriteHeader(code)
+ }
+ fw.mu.Lock()
+ fw.settleLocked()
+ fw.mu.Unlock()
+}
+
+func (fw *assetFillWriter) Write(p []byte) (int, error) {
+ if !fw.wrote {
+ fw.WriteHeader(http.StatusOK)
+ }
+ fw.n += int64(len(p))
+ fw.mu.Lock()
+ if fw.fill != nil {
+ fw.hash.Write(p)
+ if _, err := fw.fill.Write(p); err != nil {
+ // Past the reservation or the body cap, or a disk error: the
+ // rest is streamed and discarded.
+ fw.fill.Abort()
+ fw.fill = nil
+ }
+ }
+ teeBody := fw.tee && !fw.head && !fw.clientGone
+ fw.mu.Unlock()
+ if teeBody {
+ if _, err := fw.w.Write(p); err != nil {
+ fw.clientLeft()
+ }
+ }
+ fw.mu.Lock()
+ fw.settleLocked()
+ fw.mu.Unlock()
+ return len(p), nil
+}
+
+func (fw *assetFillWriter) Flush() {
+ fw.mu.Lock()
+ live := fw.headerDone && fw.tee && !fw.head && !fw.clientGone
+ fw.mu.Unlock()
+ if live {
+ _ = http.NewResponseController(fw.w).Flush()
+ }
+}
+
+// abandon is the deadline: the fill stops caching and its reservation goes
+// back now.
+func (fw *assetFillWriter) abandon() {
+ fw.mu.Lock()
+ defer fw.mu.Unlock()
+ fw.abandoned = true
+ if fw.fill != nil {
+ fw.fill.Abort()
+ fw.fill = nil
+ }
+ fw.settleLocked()
+}
+
+// clientLeft is the initiator going away.
+func (fw *assetFillWriter) clientLeft() {
+ fw.mu.Lock()
+ defer fw.mu.Unlock()
+ fw.clientGone = true
+ fw.settleLocked()
+}
+
+// settleLocked cancels the upstream request once nobody needs its bytes:
+// no fill is storing them and no initiator is being, or could still be,
+// teed them. Before the headers it waits unless the fill is abandoned and
+// the initiator gone, because the verdict is not known yet. The caller
+// holds mu.
+func (fw *assetFillWriter) settleLocked() {
+ if fw.cancelled {
+ return
+ }
+ var needed bool
+ if !fw.headerDone {
+ needed = !fw.abandoned || !fw.clientGone
+ } else {
+ needed = fw.fill != nil || (fw.tee && !fw.head && !fw.clientGone)
+ }
+ if !needed {
+ fw.cancelled = true
+ fw.cancelUp()
+ }
+}
+
+// finish runs once the upstream handler has returned: it hands any
+// trailers to a teed initiator and commits or abandons the fill.
+func (fw *assetFillWriter) finish(brokeOff bool) (*assetcache.Entry, error) {
+ if !fw.wrote {
+ if brokeOff {
+ fw.mu.Lock()
+ fw.headerDone = true
+ fw.mu.Unlock()
+ return nil, errAssetUndelivered
+ }
+ fw.WriteHeader(http.StatusOK)
+ }
+ trailers := assetTrailers(fw.snap, fw.hdr)
+
+ fw.mu.Lock()
+ defer fw.mu.Unlock()
+ teeBody := fw.tee && !fw.head && !fw.clientGone
+ if teeBody && len(trailers) > 0 {
+ h := fw.w.Header()
+ for k, vs := range trailers {
+ if vs != nil {
+ h[k] = vs
+ }
+ }
+ }
+ notStored := func(cause error) (*assetcache.Entry, error) {
+ switch {
+ case !fw.tee:
+ return nil, errAssetUndelivered
+ case brokeOff && !fw.cancelled:
+ return nil, errAssetBrokeOff
+ case cause != nil:
+ return nil, errors.Join(errAssetNotStored, cause)
+ }
+ return nil, errAssetNotStored
+ }
+ fill := fw.fill
+ fw.fill = nil
+ if fill == nil {
+ return notStored(nil)
+ }
+ if brokeOff || (fw.cl >= 0 && fw.n != fw.cl) || assetTrailerVeto(trailers) {
+ fill.Abort()
+ return notStored(nil)
+ }
+ hdr := assetStoredHeader(fw.snap)
+ if hdr.Get("ETag") == "" {
+ hdr.Set("ETag", `"`+hex.EncodeToString(fw.hash.Sum(nil))+`"`)
+ }
+ 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))
+ }
+ ent, ok := fw.st.store.Get(fw.k)
+ if !ok {
+ return notStored(cerr)
+ }
+ return ent, cerr
+}
+
+// assetTrailers collects a response's trailers from the handler's header
+// map once it has returned: every name the final headers announced in
+// Trailer (present whether or not a value came) and every unannounced one
+// under http.TrailerPrefix, the shapes assetTrailerVeto reads.
+func assetTrailers(snap, final http.Header) http.Header {
+ t := http.Header{}
+ for _, v := range snap.Values("Trailer") {
+ for _, name := range strings.Split(v, ",") {
+ if name = http.CanonicalHeaderKey(strings.TrimSpace(name)); name != "" {
+ t[name] = final[name]
+ }
+ }
+ }
+ for k, vs := range final {
+ if strings.HasPrefix(k, http.TrailerPrefix) {
+ t[k] = vs
+ }
+ }
+ return t
+}
+
+// stripAssetResponseHeaders deletes the asset cache's vocabulary from an
+// app's response: the fill, acknowledgement and expiry headers and
+// Carlos-Cache are the platform's to set, never the app's (§5.3).
+func stripAssetResponseHeaders(h http.Header) {
+ h.Del(assetFillHeader)
+ h.Del(assetAckHeader)
+ h.Del(assetExpiresHeader)
+ h.Del(assetCacheHeader)
+}
diff --git a/internal/edge/cookiescope.go b/internal/edge/cookiescope.go
index ca9aa374c..ba197ee11 100644
--- a/internal/edge/cookiescope.go
+++ b/internal/edge/cookiescope.go
@@ -71,14 +71,17 @@ func appsDomainFromEnv() string {
}
// responseModifier is the ModifyResponse hook for a tenant route's reverse
-// proxy: the Carlos-Purge channel (purgeModifier) and the cookie scoping
-// above, in that order. Neither depends on the other.
+// proxy: the Carlos-Purge channel (purgeModifier), the removal of any asset
+// cache header the app set (stripAssetResponseHeaders: the edge's own are
+// set after this, never inherited from the app) and the cookie scoping
+// above, in that order. None depends on another.
func (e *Edge) responseModifier(rt registry.Route) func(*http.Response) error {
purge := e.purgeModifier(rt)
return func(resp *http.Response) error {
if err := purge(resp); err != nil {
return err
}
+ stripAssetResponseHeaders(resp.Header)
e.scopeCookies(rt, resp)
return nil
}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 0e0020e34..9c48190f3 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -249,6 +249,10 @@ type Edge struct {
// quietly 503s. Never stopped in production (the edge lives as long as the
// process); tests Stop it so probe goroutines don't outlive them.
probers *proberSet
+ // assets, when non-nil, is the armed edge asset cache (assetcatch.go):
+ // the disk store, the home's own catch and the fill coalescer. Nil (every
+ // box until Task 7's arming) keeps every request on today's path.
+ assets *assetState
// gzipOn is the CARLOS_EDGE_GZIP kill switch, read once in New. When
// false, ServeHTTP never constructs a gzipWriter and the writer stack is
// byte-for-byte what it was before compression existed (compress.go).
@@ -1741,7 +1745,10 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var out *outcome
r, out = withOutcome(r)
defer func() {
- if m := e.usageMeter.Load(); m != nil {
+ // An acknowledged home fill is billed by the far edge that
+ // delivers it (assetcatch.go); every other observer below
+ // still sees it.
+ if m := e.usageMeter.Load(); m != nil && !out.unbilled {
m.Record(up.route, 1, bytes, hopped)
}
if ob.status >= 500 && !out.answered {
@@ -1752,6 +1759,16 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}()
}
+ // The home side of a far edge's asset fill (assetcatch.go, design
+ // §5.3): a verified hop carrying a valid fill assertion is answered from
+ // this box's asset cache or filled from the app, acknowledged, and left
+ // unbilled. After the observer defer, so only billing is skipped (plan 3
+ // drift D9); before the password gate, the shared cache and the
+ // activator, none of which it touches (it never answers a gated route).
+ if hopped && e.serveAssetFillForHop(w, r, host, up) {
+ return
+ }
+
// The password gate (internal/gate; spec 2026-09-07-password-gate-design
// §4.1). Placed HERE and the neighbours are load-bearing: after the
// meter, so the login page's bytes bill to the route that caused them;
@@ -1817,6 +1834,18 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
+ // The local asset catch (assetcatch.go, design §5.1): a declared asset
+ // path on a route this box holds is answered from the disk store or
+ // filled from the app. After the upgrade branch, so an upgrade under a
+ // prefix keeps its writer stack; before the gzip wrapper, because a
+ // caught response writes its own representation, and before the shared
+ // cache, which caught requests never read or fill. It passes the plan
+ // throttle itself (a hit still spends bandwidth) and the rate limit for
+ // what reaches the app.
+ if e.serveAssetLocal(w, r, host, up) {
+ return
+ }
+
// Response compression (compress.go). Placed AFTER the upgrade branch, so
// an upgrading request keeps the exact writer stack it has always had —
// purge_header.go's contract records what wrapping the raw ResponseWriter