| 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") |
| + } |
| +} |