edge: two-edge acceptance for the asset cache (asset cache plan 3 Task 9)
Spec 12's attack matrix through production wiring: two real Edges over one DirStore with real TLS, mesh keys, hop auth and backhaul, each armed through EnableAssetCache with a real store, and the home's edges-file entry read from the writer-pinned golden with only its at rebased (D14). Miss then hit, gzip from the far edge, purge, an old far edge's forged marker billed as a hop, a disarmed home, credentials, every refusal, a late veto on a buffered range, coalescing, a stalled body, undeclaring builds and a warm sleep and restart on a generation-managed instance (genManaged asserted first, D15), the far catch behind a local wildcard, oversized bodies, and generation or owner mismatches. Tests only; no production defect found.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+1,064
−0
internal/edge/asset_e2e_test.go+1,064 −0
diff --git a/internal/edge/asset_e2e_test.go b/internal/edge/asset_e2e_test.go| new file mode 100644 |
| index 000000000..1422d041f |
| --- /dev/null |
| +++ b/internal/edge/asset_e2e_test.go |
| @@ -0,0 +1,1064 @@ |
| +package edge |
| + |
| +// Task 9 of the edge asset cache's plan 3: the two-edge acceptance gate |
| +// (design §12). The scene is the multi-region backhaul's (newBackhaulScene): |
| +// two real Edges over one DirStore, real TLS on both doors with a test CA, |
| +// the mesh key minted into the bucket and mirrored by each edge's home map, |
| +// real hop auth and real backhaul. On top of it each edge is armed through |
| +// EnableAssetCache with a real plan 2 store on its own temporary directory, |
| +// and the home edge's edges file carries the asset host's entry as read |
| +// from internal/edgesfile/testdata/assets-host.golden.json, the file the |
| +// writer's own test (internal/host TestPublishesAssetsForAnArmedHome) pins. |
| +// |
| +// Edge A ("annie") homes shop.example.com and runs its app; edge B |
| +// ("betty") has no route for it and learns it, and its asset block, only |
| +// from annie's edges file. Every far request below is a real client's, |
| +// handshaken with betty by name, and every fill is the real signed hop. |
| +// |
| +// Two things are fixtures rather than production code, and they are named |
| +// so: the home's LocalAssets is fakeLocalAssets answering exactly what the |
| +// golden publishes (internal/host's assetPolicy cannot be imported here; it |
| +// is the writer whose output the golden pins), and a generation-managed |
| +// instance runs behind genActivator, Task 5's hand-driven GenSource. |
| +// |
| +// The golden's "at" is fixed. It is rebased to the test clock after the |
| +// golden is read (plan 3 drift D14), and nothing else in it is changed |
| +// except where a test is about changing it (a purge's generation). The |
| +// clocks stay real: hop auth is checked by acceptHop against time.Now, so |
| +// every signature here is made with time.Now too. |
| + |
| +import ( |
| + "crypto/rand" |
| + "encoding/hex" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/assetcache" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// e2eGen2 is the generation a purge draws. |
| +const e2eGen2 = "fedcba9876543210" |
| + |
| +// e2eGoldenView is the golden host entry, parsed into the edge's own reading |
| +// of an edges-file host (edgesHostView, which carries the owner: the shared |
| +// edgesfile.Host does not), with at rebased to now. |
| +func e2eGoldenView(t *testing.T, now time.Time) edgesHostView { |
| + t.Helper() |
| + var v edgesHostView |
| + if err := json.Unmarshal([]byte(assetsGolden(t)), &v); err != nil { |
| + t.Fatalf("parse the golden: %v", err) |
| + } |
| + if v.Assets == nil || v.Assets.At != goldenAt.Unix() || v.Assets.Primary != laHost || v.Account == "" || v.App == "" { |
| + t.Fatalf("test bug: the golden is not the entry this file was written for: %+v %+v", v, v.Assets) |
| + } |
| + v.Assets.At = now.Unix() |
| + return v |
| +} |
| + |
| +// e2eGoldenEntry is the golden entry as JSON, rebased to now, with edit |
| +// applied (nil for none). |
| +func e2eGoldenEntry(t *testing.T, now time.Time, edit func(*edgesHostView)) string { |
| + t.Helper() |
| + v := e2eGoldenView(t, now) |
| + if edit != nil { |
| + edit(&v) |
| + } |
| + b, err := json.Marshal(v) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(b) |
| +} |
| + |
| +// e2eGoldenAssets is the home's own answer for the host: what its policy |
| +// snapshot holds when the golden is what its writer published. |
| +func e2eGoldenAssets(t *testing.T) HostAssets { |
| + t.Helper() |
| + v := e2eGoldenView(t, time.Now()) |
| + return HostAssets{Account: v.Account, App: v.App, Paths: append([]string(nil), v.Assets.Paths...), |
| + Gen: v.Assets.Gen, At: time.Unix(v.Assets.At, 0), Primary: v.Assets.Primary} |
| +} |
| + |
| +// assetE2E is the armed two-edge scene. |
| +type assetE2E struct { |
| + *backhaulScene |
| + app *laBackend // the home's app, on TCP (nil on a generation scene) |
| + local *fakeLocalAssets // the home's policy snapshot |
| + route registry.Route // the home's route row for laHost |
| + aStore, bStore *assetcache.Store |
| + aDir, bDir string |
| + aMeter, bMeter *UsageMeter |
| + aTap *e2eTap |
| +} |
| + |
| +type assetE2EOpts struct { |
| + // handler is the home's TCP app; nil when route makes the route a socket. |
| + handler http.HandlerFunc |
| + // route edits the home's route row before the edge is built. |
| + route func(*registry.Route) |
| + // act is the home edge's activator. |
| + act Activator |
| + // farRoutes are routes of the far edge's own. |
| + farRoutes []registry.Route |
| + // homeUnarmed leaves the home edge's asset cache off; its edges file |
| + // still carries the asset block, as one written before it was disarmed. |
| + homeUnarmed bool |
| +} |
| + |
| +func newAssetE2E(t *testing.T, o assetE2EOpts) *assetE2E { |
| + t.Helper() |
| + x := &assetE2E{ |
| + route: registry.Route{Host: laHost, Kind: "instance", Status: "ready", |
| + Account: "abc", App: "shop", AssetGen: laGen, Version: laBuild}, |
| + local: &fakeLocalAssets{hosts: map[string]HostAssets{}, builds: map[string]bool{}}, |
| + aMeter: NewUsageMeter(), bMeter: NewUsageMeter(), aTap: &e2eTap{}, |
| + } |
| + if o.handler != nil { |
| + x.app = newLABackend(t, o.handler) |
| + x.route.Addr = x.app.srv.Listener.Addr().String() |
| + } |
| + if o.route != nil { |
| + o.route(&x.route) |
| + } |
| + golden := e2eGoldenAssets(t) |
| + if golden.Account != x.route.Account || golden.App != x.route.App || golden.Gen != x.route.AssetGen { |
| + t.Fatalf("test bug: the route %+v is not the golden's owner and generation %+v", x.route, golden) |
| + } |
| + x.backhaulScene = newBackhaulSceneWith(t, backhaulSceneExtra{ |
| + homeRoutes: []registry.Route{x.route}, |
| + farRoutes: o.farRoutes, |
| + homeAct: o.act, |
| + certs: []string{laHost}, |
| + homeEntries: map[string]string{laHost: e2eGoldenEntry(t, time.Now(), nil)}, |
| + }) |
| + x.converge(t) |
| + |
| + // Production wiring: every edge has the shared LRU (RunWithActivator), |
| + // so a caught request is seen not to read or fill it. |
| + for _, be := range []*backhaulEdge{x.a, x.b} { |
| + be.edge.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes)) |
| + } |
| + x.local.set(laHost, golden) |
| + x.local.declare(laBuild, true) |
| + x.aDir = filepath.Join(t.TempDir(), "asset-cache") |
| + x.bDir = filepath.Join(t.TempDir(), "asset-cache") |
| + x.aStore, x.bStore = openStoreAt(t, x.aDir), openStoreAt(t, x.bDir) |
| + if !o.homeUnarmed { |
| + armForTest(t, x.a.edge, x.aStore, x.local) |
| + } |
| + armForTest(t, x.b.edge, x.bStore, &fakeLocalAssets{hosts: map[string]HostAssets{}, builds: map[string]bool{}}) |
| + x.a.edge.EnableUsage(x.aMeter) |
| + x.b.edge.EnableUsage(x.bMeter) |
| + x.a.tap.Store(x.aTap) |
| + |
| + // The premise, asserted: betty has no route for the host, and knows its |
| + // asset block only from annie's file. |
| + if _, ok := x.b.edge.lookupUpstream(laHost); ok && len(o.farRoutes) == 0 { |
| + t.Fatal("test bug: the far edge must not route the asset host") |
| + } |
| + if a, ok := x.b.homes.AssetsFor(laHost, time.Now()); !ok || a.Gen != laGen || a.Account != "abc" || a.App != "shop" { |
| + t.Fatalf("the far edge's home map holds no asset block for %s from the golden: %+v %v", laHost, a, ok) |
| + } |
| + if eip, box, ok := x.b.homes.ExactHome(laHost); !ok || box != "annie" || eip != x.aEIP { |
| + t.Fatalf("the far edge's map homes %s at %s %s %v, want annie", laHost, eip, box, ok) |
| + } |
| + return x |
| +} |
| + |
| +// fetch is one client request for laHost at be. Accept-Encoding defaults to |
| +// identity, so the client's transport neither asks for gzip nor undoes it. |
| +func (x *assetE2E) fetch(t *testing.T, be *backhaulEdge, path string, hdr ...string) (*http.Response, string) { |
| + t.Helper() |
| + return x.get(t, be, "https://"+laHost+path, e2eHeaders(hdr), true) |
| +} |
| + |
| +func e2eHeaders(hdr []string) map[string]string { |
| + h := map[string]string{"Accept-Encoding": "identity"} |
| + for i := 0; i+1 < len(hdr); i += 2 { |
| + h[hdr[i]] = hdr[i+1] |
| + } |
| + return h |
| +} |
| + |
| +type e2eResult struct { |
| + resp *http.Response |
| + body string |
| + err error |
| +} |
| + |
| +// fetchAsync is fetch on its own goroutine. |
| +func (x *assetE2E) fetchAsync(be *backhaulEdge, path string, hdr ...string) <-chan e2eResult { |
| + ch := make(chan e2eResult, 1) |
| + go func() { |
| + resp, err := x.try(be, "https://"+laHost+path, e2eHeaders(hdr), true) |
| + if err != nil { |
| + ch <- e2eResult{err: err} |
| + return |
| + } |
| + b, err := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + ch <- e2eResult{resp: resp, body: string(b), err: err} |
| + }() |
| + return ch |
| +} |
| + |
| +func e2eAwait(t *testing.T, ch <-chan e2eResult) e2eResult { |
| + t.Helper() |
| + select { |
| + case r := <-ch: |
| + if r.err != nil { |
| + t.Fatalf("request: %v", r.err) |
| + } |
| + return r |
| + case <-time.After(30 * time.Second): |
| + t.Fatal("a request never finished") |
| + } |
| + return e2eResult{} |
| +} |
| + |
| +func wantE2ECache(t *testing.T, resp *http.Response, want string) { |
| + t.Helper() |
| + if got := resp.Header.Get(assetCacheHeader); got != want { |
| + t.Fatalf("Carlos-Cache = %q, want %q (status %d)", got, want, resp.StatusCode) |
| + } |
| + for _, h := range []string{assetFillHeader, assetAckHeader, assetExpiresHeader} { |
| + if v := resp.Header.Values(h); len(v) > 0 { |
| + t.Fatalf("the client received %s %q", h, v) |
| + } |
| + } |
| +} |
| + |
| +func (x *assetE2E) entryKey(path string) assetcache.Key { |
| + return assetcache.Key{Account: "abc", App: "shop", Gen: laGen, Host: laHost, Path: path} |
| +} |
| + |
| +// wantNothingStored: neither store holds an entry or a reservation. |
| +func (x *assetE2E) wantNothingStored(t *testing.T, what string) { |
| + t.Helper() |
| + for name, st := range map[string]*assetcache.Store{"home": x.aStore, "far": x.bStore} { |
| + if s := st.Stats(); s.Entries != 0 || s.Reserved != 0 { |
| + t.Fatalf("%s: the %s store holds %+v, want nothing", what, name, s) |
| + } |
| + } |
| +} |
| + |
| +// rows drains both meters' rows for laHost. |
| +func (x *assetE2E) rows() (home, far usageRowView) { |
| + return rowOf(x.aMeter), rowOf(x.bMeter) |
| +} |
| + |
| +type usageRowView struct { |
| + requests, bytes, hopRequests, hopBytes int64 |
| +} |
| + |
| +func rowOf(m *UsageMeter) usageRowView { |
| + r := m.Drain()[laHost] |
| + return usageRowView{r.Requests, r.BytesOut, r.HopRequests, r.HopBytesOut} |
| +} |
| + |
| +// wantMeteredOnce: the two edges together record exactly one request for |
| +// laHost, on the edge named, the other recording nothing. |
| +func (x *assetE2E) wantMeteredOnce(t *testing.T, at string) (home, far usageRowView) { |
| + t.Helper() |
| + home, far = x.rows() |
| + if home.requests+far.requests != 1 { |
| + t.Fatalf("metered home %+v far %+v, want one request in total", home, far) |
| + } |
| + if (at == "home") != (home.requests == 1) { |
| + t.Fatalf("metered home %+v far %+v, want the one request at the %s edge", home, far, at) |
| + } |
| + return home, far |
| +} |
| + |
| +func e2eLRULen(e *Edge) int { |
| + e.cache.mu.Lock() |
| + defer e.cache.mu.Unlock() |
| + return len(e.cache.entries) |
| +} |
| + |
| +// setHome rewrites the home's route row (edit applied to the current one) |
| +// and reloads the edge, and moves the home's policy snapshot to the same |
| +// owner and generation: the home has moved on. The far edge's view does not |
| +// move until the home's edges file is republished and the maps converge. |
| +func (x *assetE2E) setHome(t *testing.T, edit func(*registry.Route)) { |
| + t.Helper() |
| + edit(&x.route) |
| + if err := x.a.edge.reg.Upsert(x.route); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := x.a.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + a := e2eGoldenAssets(t) |
| + a.Account, a.App, a.Gen = x.route.Account, x.route.App, x.route.AssetGen |
| + x.local.set(laHost, a) |
| +} |
| + |
| +// ---- miss, hit, gzip, purge ------------------------------------------------- |
| + |
| +func TestAssetE2EFarMissThenHit(t *testing.T) { |
| + x := newAssetE2E(t, assetE2EOpts{handler: assetOK(laBody)}) |
| + |
| + resp, body := x.fetch(t, x.b, "/assets/app.js") |
| + wantE2ECache(t, resp, "miss") |
| + if resp.StatusCode != http.StatusOK || body != laBody { |
| + t.Fatalf("miss = %d %q", resp.StatusCode, body) |
| + } |
| + // On the wire between the two edges: one signed hop carrying an |
| + // assertion, answered with an acknowledgement that verifies under the |
| + // deployment's key for the entry's expiry. |
| + req, out := x.aTap.last() |
| + assertion := req.Get(assetFillHeader) |
| + if req.Get(hopHeader) != "1" || req.Get(hopAuthHeader) == "" || assertion == "" { |
| + t.Fatalf("the fill reached the home as %v, want a signed hop with an assertion", req) |
| + } |
| + exp, err := strconv.ParseInt(out.Get(assetExpiresHeader), 10, 64) |
| + if err != nil || exp == 0 || !verifyAssetAck(x.key, assertion, exp, out.Get(assetAckHeader)) { |
| + t.Fatalf("the home's answer carried expiry %q ack %q, want a verifying acknowledgement", |
| + out.Get(assetExpiresHeader), out.Get(assetAckHeader)) |
| + } |
| + |
| + resp, body = x.fetch(t, x.b, "/assets/app.js") |
| + wantE2ECache(t, resp, "hit") |
| + if resp.StatusCode != http.StatusOK || body != laBody { |
| + t.Fatalf("hit = %d %q", resp.StatusCode, body) |
| + } |
| + if n := x.app.n.Load(); n != 1 { |
| + t.Fatalf("the home's app saw %d requests, want exactly one", n) |
| + } |
| + if n := x.a.calls.Load(); n != 1 { |
| + t.Fatalf("the home edge saw %d requests, want the one fill", n) |
| + } |
| + for name, st := range map[string]*assetcache.Store{"home": x.aStore, "far": x.bStore} { |
| + ent, ok := st.Get(x.entryKey("/assets/app.js")) |
| + if !ok { |
| + t.Fatalf("the %s store holds no entry", name) |
| + } |
| + if ent.Meta.Expires.Unix() != exp { |
| + t.Fatalf("the %s entry expires at %v, want the home's acknowledged %d", name, ent.Meta.Expires, exp) |
| + } |
| + } |
| + // Metered once per delivery, at the far edge, under the published |
| + // owner; the home billed nothing for the acknowledged fill. |
| + home, far := x.rows() |
| + if far.requests != 2 || far.bytes != int64(2*len(laBody)) || home.requests != 0 { |
| + t.Fatalf("metered home %+v far %+v, want two deliveries at the far edge", home, far) |
| + } |
| + if n, m := e2eLRULen(x.a.edge), e2eLRULen(x.b.edge); n != 0 || m != 0 { |
| + t.Fatalf("the shared LRUs hold %d and %d entries, want none", n, m) |
| + } |
| +} |
| + |
| +func TestAssetE2EGzipFromTheFarEdge(t *testing.T) { |
| + const size = 5 << 20 |
| + rule := ".bundle{color:#123456;margin:0 auto}\n" |
| + css := strings.Repeat(rule, size/len(rule)+1)[:size] |
| + x := newAssetE2E(t, assetE2EOpts{handler: func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "text/css") |
| + w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") |
| + w.Header().Set("Content-Length", strconv.Itoa(len(css))) |
| + io.WriteString(w, css) |
| + }}) |
| + |
| + resp, body := x.fetch(t, x.b, "/assets/bundle.css", "Accept-Encoding", "gzip") |
| + wantE2ECache(t, resp, "miss") |
| + if enc := resp.Header.Get("Content-Encoding"); enc != "" || body != css { |
| + t.Fatalf("miss = %d bytes encoded %q, want the identity bundle as it streamed", len(body), enc) |
| + } |
| + |
| + resp, body = x.fetch(t, x.b, "/assets/bundle.css", "Accept-Encoding", "gzip") |
| + wantE2ECache(t, resp, "hit") |
| + if enc := resp.Header.Get("Content-Encoding"); enc != "gzip" { |
| + t.Fatalf("hit Content-Encoding = %q, want gzip", enc) |
| + } |
| + if len(body) >= size/4 { |
| + t.Fatalf("the gzip hit is %d bytes for a %d-byte bundle", len(body), size) |
| + } |
| + if got := string(gunzipBytes(t, []byte(body))); got != css { |
| + t.Fatalf("the gzip hit decompresses to %d bytes, want the %d-byte bundle", len(got), size) |
| + } |
| + if !varyNamesAcceptEncoding(resp.Header) { |
| + t.Fatalf("gzip hit Vary = %q, want Accept-Encoding", resp.Header.Values("Vary")) |
| + } |
| + weak := resp.Header.Get("ETag") |
| + if !strings.HasPrefix(weak, `W/"`) { |
| + t.Fatalf("gzip hit ETag = %q, want a weak validator", weak) |
| + } |
| + |
| + // The identity representation of the same entry: Vary too, and the |
| + // strong ETag the weak one was made from. |
| + resp, body = x.fetch(t, x.b, "/assets/bundle.css") |
| + wantE2ECache(t, resp, "hit") |
| + if resp.Header.Get("Content-Encoding") != "" || body != css || !varyNamesAcceptEncoding(resp.Header) { |
| + t.Fatalf("identity hit = %d bytes, encoding %q, Vary %q", len(body), resp.Header.Get("Content-Encoding"), resp.Header.Values("Vary")) |
| + } |
| + if strong := resp.Header.Get("ETag"); "W/"+strong != weak { |
| + t.Fatalf("identity ETag %q is not the strong form of %q", strong, weak) |
| + } |
| + if n := x.app.n.Load(); n != 1 { |
| + t.Fatalf("the home's app saw %d requests, want one", n) |
| + } |
| +} |
| + |
| +func TestAssetE2EPurgeMakesEveryEdgeMiss(t *testing.T) { |
| + x := newAssetE2E(t, assetE2EOpts{handler: assetOK(laBody)}) |
| + round := func(want string) { |
| + t.Helper() |
| + for _, be := range []*backhaulEdge{x.a, x.b} { |
| + resp, body := x.fetch(t, be, "/assets/app.js") |
| + wantE2ECache(t, resp, want) |
| + if body != laBody { |
| + t.Fatalf("body = %q", body) |
| + } |
| + } |
| + } |
| + round("miss") |
| + round("hit") |
| + if n := x.app.n.Load(); n != 1 { |
| + t.Fatalf("the app saw %d requests warming, want 1", n) |
| + } |
| + |
| + // The purge: a fresh generation on the home's record (its route row |
| + // and its policy snapshot), and the home's edges file rewritten with |
| + // it. One home-map poll later every edge misses once. |
| + x.setHome(t, func(rt *registry.Route) { rt.AssetGen = e2eGen2 }) |
| + x.publishHomeEdgesFile(t, map[string]string{laHost: e2eGoldenEntry(t, time.Now(), func(v *edgesHostView) { v.Assets.Gen = e2eGen2 })}) |
| + x.converge(t) |
| + if a, ok := x.b.homes.AssetsFor(laHost, time.Now()); !ok || a.Gen != e2eGen2 { |
| + t.Fatalf("the far edge's map holds %+v %v after the poll, want generation %s", a, ok, e2eGen2) |
| + } |
| + round("miss") |
| + round("hit") |
| + if n := x.app.n.Load(); n != 2 { |
| + t.Fatalf("the app saw %d requests, want one more after the purge", n) |
| + } |
| +} |
| + |
| +// ---- billing and the protocol's edges ---------------------------------------- |
| + |
| +// An old far edge forwards whatever its client sent and signs the hop. Built |
| +// here by hand, since a new edge strips a client's marker whether or not it |
| +// is armed: a valid hop signature under the scene's mesh key, and a forged |
| +// assertion with a well-formed timestamp and a random MAC. |
| +func TestAssetE2EOldFarEdgeForgedMarkerIsBilledAsAHop(t *testing.T) { |
| + x := newAssetE2E(t, assetE2EOpts{handler: assetOK(laBody)}) |
| + mac := make([]byte, 32) |
| + if _, err := rand.Read(mac); err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Now() |
| + forged := fmt.Sprintf("%d:%s", now.Unix(), hex.EncodeToString(mac)) |
| + resp, body := x.get(t, x.a, "https://"+laHost+"/assets/app.js", map[string]string{ |
| + hopHeader: "1", |
| + hopAuthHeader: signHop(x.key, laHost, now), |
| + assetFillHeader: forged, |
| + "X-Forwarded-For": "203.0.113.9", |
| + "Accept-Encoding": "identity", |
| + }, true) |
| + if resp.StatusCode != http.StatusOK || body != laBody { |
| + t.Fatalf("the hop = %d %q", resp.StatusCode, body) |
| + } |
| + req, out := x.aTap.last() |
| + if req.Get(assetFillHeader) != forged || req.Get(hopHeader) != "1" { |
| + t.Fatalf("the home edge received %v, want the hop and its forged marker", req) |
| + } |
| + for _, h := range []string{assetAckHeader, assetExpiresHeader} { |
| + if v := out.Values(h); len(v) > 0 { |
| + t.Fatalf("the home answered a forged marker with %s %q", h, v) |
| + } |
| + } |
| + if got := x.app.lastReq().Header.Get(assetFillHeader); got != "" { |
| + t.Fatalf("the forged marker reached the app: %q", got) |
| + } |
| + // Billed as an ordinary hop (TestHopServedRequestMetersOnceWithHopCounters' |
| + // counters): the hop verified, so the one request is annotated as |
| + // hopped; the marker bought no exemption. |
| + home, far := x.rows() |
| + if home.requests != 1 || home.hopRequests != 1 || home.bytes == 0 || home.hopBytes != home.bytes || far.requests != 0 { |
| + t.Fatalf("metered home %+v far %+v, want one hopped request at the home", home, far) |
| + } |
| +} |
| + |
| +func TestAssetE2EDisarmedHomeFillsNothing(t *testing.T) { |
| + x := newAssetE2E(t, assetE2EOpts{handler: assetOK(laBody), homeUnarmed: true}) |
| + for i := 0; i < 2; i++ { |
| + resp, body := x.fetch(t, x.b, "/assets/app.js") |
| + wantE2ECache(t, resp, "bypass") |
| + if resp.StatusCode != http.StatusOK || body != laBody { |
| + t.Fatalf("request %d = %d %q", i, resp.StatusCode, body) |
| + } |
| + req, out := x.aTap.last() |
| + if req.Get(assetFillHeader) == "" { |
| + t.Fatal("test bug: the far edge sent no fill, so the disarmed home was never asked") |
| + } |
| + if out.Get(assetAckHeader) != "" || out.Get(assetExpiresHeader) != "" { |
| + t.Fatalf("a disarmed home acknowledged a fill: %v", out) |
| + } |
| + x.wantMeteredOnce(t, "home") |
| + } |
| + // An unarmed home is today's edge: its shared LRU answered the repeat. |
| + if n, lru := x.app.n.Load(), e2eLRULen(x.a.edge); n != 1 || lru != 1 { |
| + t.Fatalf("the app saw %d requests and the home's shared LRU holds %d entries, want 1 and 1", n, lru) |
| + } |
| + if n := x.a.calls.Load(); n != 2 { |
| + t.Fatalf("the home edge saw %d requests, want both", n) |
| + } |
| + x.wantNothingStored(t, "a disarmed home") |
| +} |
| + |
| +func TestAssetE2EFillCarriesNoCredentials(t *testing.T) { |
| + x := newAssetE2E(t, assetE2EOpts{handler: assetOK(laBody)}) |
| + resp, _ := x.fetch(t, x.b, "/assets/app.js", "Cookie", "session=secret", "Authorization", "Bearer secret") |
| + wantE2ECache(t, resp, "miss") |
| + got := x.app.lastReq() |
| + for _, h := range []string{"Cookie", "Authorization", assetFillHeader, hopHeader, hopAuthHeader} { |
| + if v := got.Header.Values(h); len(v) > 0 { |
| + t.Fatalf("the home's app received %s %q", h, v) |
| + } |
| + } |
| + // Nor did they cross the hop at all. |
| + req, _ := x.aTap.last() |
| + if req.Get("Cookie") != "" || req.Get("Authorization") != "" { |
| + t.Fatalf("the fill carried the client's credentials to the home: %v", req) |
| + } |
| + resp, _ = x.fetch(t, x.b, "/assets/app.js", "Cookie", "session=secret", "Authorization", "Bearer secret") |
| + wantE2ECache(t, resp, "hit") |
| + if n := x.app.n.Load(); n != 1 { |
| + t.Fatalf("the app saw %d requests, want 1", n) |
| + } |
| +} |
| + |
| +// A refusing response through the far edge: served as it came, stored on |
| +// neither edge, metered once. The home acknowledges each fill with expiry 0 |
| +// (refused at header time), so the far edge meters it; the Set-Cookie |
| +// trailer and nothing else is admitted at header time, so it alone is |
| +// answered miss (the header was written while it was being filled) and |
| +// vetoed after the body, on both edges. |
| +func TestAssetE2ERefusedFillsAreStoredNowhere(t *testing.T) { |
| + plain := func(status int, kv ...string) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + for i := 0; i+1 < len(kv); i += 2 { |
| + w.Header().Set(kv[i], kv[i+1]) |
| + } |
| + w.WriteHeader(status) |
| + io.WriteString(w, laBody) |
| + } |
| + } |
| + trailer := 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.(http.Flusher).Flush() |
| + w.Header().Set("Set-Cookie", "late=1") |
| + } |
| + cases := []struct { |
| + name string |
| + h http.HandlerFunc |
| + status int |
| + cache string |
| + }{ |
| + {"set-cookie", assetOK(laBody, "Set-Cookie", "s=1"), 200, "bypass"}, |
| + {"set-cookie-trailer", trailer, 200, "miss"}, |
| + {"vary-cookie", assetOK(laBody, "Vary", "Cookie"), 200, "bypass"}, |
| + {"vary-origin", assetOK(laBody, "Vary", "Origin"), 200, "bypass"}, |
| + {"private", assetOK(laBody, "Cache-Control", "private, max-age=3600"), 200, "bypass"}, |
| + {"no-cache", assetOK(laBody, "Cache-Control", "public, no-cache, max-age=3600"), 200, "bypass"}, |
| + {"no-store", assetOK(laBody, "Cache-Control", "no-store"), 200, "bypass"}, |
| + {"no-cache-control", plain(200, "Content-Type", "application/javascript"), 200, "bypass"}, |
| + {"partial", plain(206, "Content-Type", "application/javascript", "Cache-Control", "public, max-age=3600", |
| + "Content-Range", fmt.Sprintf("bytes 0-%d/%d", len(laBody)-1, len(laBody)+10)), 206, "bypass"}, |
| + {"html-fallback", plain(200, "Content-Type", "text/html; charset=utf-8", "Cache-Control", "public, max-age=31536000"), 200, "bypass"}, |
| + {"not-found", plain(404, "Content-Type", "application/javascript", "Cache-Control", "public, max-age=3600"), 404, "bypass"}, |
| + } |
| + byPath := map[string]http.HandlerFunc{} |
| + for _, c := range cases { |
| + byPath["/assets/"+c.name+".js"] = c.h |
| + } |
| + x := newAssetE2E(t, assetE2EOpts{handler: func(w http.ResponseWriter, r *http.Request) { byPath[r.URL.Path](w, r) }}) |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + resp, body := x.fetch(t, x.b, "/assets/"+c.name+".js") |
| + wantE2ECache(t, resp, c.cache) |
| + if resp.StatusCode != c.status || body != laBody { |
| + t.Fatalf("served %d %q, want the app's %d as it came", resp.StatusCode, body, c.status) |
| + } |
| + if c.name == "set-cookie" && resp.Header.Get("Set-Cookie") != "s=1" { |
| + t.Fatalf("the requester lost its own Set-Cookie: %v", resp.Header) |
| + } |
| + if c.name == "set-cookie-trailer" && resp.Trailer.Get("Set-Cookie") != "late=1" { |
| + t.Fatalf("the requester lost its own Set-Cookie trailer: %v", resp.Trailer) |
| + } |
| + _, out := x.aTap.last() |
| + if c.name != "set-cookie-trailer" && out.Get(assetExpiresHeader) != "0" { |
| + t.Fatalf("the home acknowledged with expiry %q, want 0 (refused at header time)", out.Get(assetExpiresHeader)) |
| + } |
| + x.wantNothingStored(t, c.name) |
| + x.wantMeteredOnce(t, "far") |
| + }) |
| + } |
| +} |
| + |
| +// A cold Range through the far edge is buffered (answered from the entry it |
| +// fills); the acknowledged fill is then vetoed by a Set-Cookie trailer, so |
| +// the client is answered by the re-forward, an ordinary backhaul the home |
| +// meters. The fill itself was acknowledged and so billed by nobody. |
| +func TestAssetE2ELateVetoOnABufferedRangeBillsOnce(t *testing.T) { |
| + x := newAssetE2E(t, assetE2EOpts{handler: 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") |
| + if r.Header.Get("Range") == "bytes=0-9" { |
| + w.Header().Set("Content-Range", fmt.Sprintf("bytes 0-9/%d", len(laBody))) |
| + w.WriteHeader(http.StatusPartialContent) |
| + io.WriteString(w, laBody[:10]) |
| + } else { |
| + io.WriteString(w, laBody) |
| + } |
| + w.(http.Flusher).Flush() |
| + w.Header().Set("Set-Cookie", "late=1") |
| + }}) |
| + resp, body := x.fetch(t, x.b, "/assets/app.js", "Range", "bytes=0-9") |
| + wantE2ECache(t, resp, "bypass") |
| + if resp.StatusCode != http.StatusPartialContent || body != laBody[:10] { |
| + t.Fatalf("range = %d %q, want the re-forward's 206 of the first ten bytes", resp.StatusCode, body) |
| + } |
| + x.wantNothingStored(t, "a vetoed range fill") |
| + home, far := x.wantMeteredOnce(t, "home") |
| + if home.bytes+far.bytes != 10 { |
| + t.Fatalf("metered home %+v far %+v, want only the ten delivered bytes", home, far) |
| + } |
| + if n := x.a.calls.Load(); n != 2 { |
| + t.Fatalf("the home edge saw %d requests, want the fill and the re-forward", n) |
| + } |
| +} |
| + |
| +func TestAssetE2ECoalescedWaitersAndRefusals(t *testing.T) { |
| + const waiters = 3 |
| + for _, tc := range []struct { |
| + name string |
| + extra []string |
| + admit bool |
| + appWant int64 |
| + }{ |
| + {"an admitted entry is shared", nil, true, 1}, |
| + {"a refusal reaches only its initiator", []string{"Set-Cookie", "s=1"}, false, 1 + waiters}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + first, started, wait, release := fillGate() |
| + x := newAssetE2E(t, assetE2EOpts{handler: func(w http.ResponseWriter, r *http.Request) { |
| + if first() { |
| + close(started) |
| + wait() |
| + } |
| + assetOK(laBody, tc.extra...)(w, r) |
| + }}) |
| + t.Cleanup(release) |
| + lead := x.fetchAsync(x.b, "/assets/app.js") |
| + <-started |
| + var rest []<-chan e2eResult |
| + for i := 0; i < waiters; i++ { |
| + rest = append(rest, x.fetchAsync(x.b, "/assets/app.js")) |
| + } |
| + laWaitFor(t, "the waiters to join the far fill", func() bool { |
| + return flightWaitersOf(x.b.edge, x.entryKey("/assets/app.js").ID()) == waiters |
| + }) |
| + release() |
| + |
| + r := e2eAwait(t, lead) |
| + want := "miss" |
| + if !tc.admit { |
| + want = "bypass" |
| + } |
| + wantE2ECache(t, r.resp, want) |
| + for _, ch := range rest { |
| + r := e2eAwait(t, ch) |
| + if r.body != laBody { |
| + t.Fatalf("waiter body = %q", r.body) |
| + } |
| + if tc.admit { |
| + wantE2ECache(t, r.resp, "hit") |
| + } else { |
| + wantE2ECache(t, r.resp, "bypass") |
| + if r.resp.Header.Get("Set-Cookie") != "s=1" { |
| + t.Fatal("a waiter's own response lost its Set-Cookie") |
| + } |
| + } |
| + } |
| + if n := x.app.n.Load(); n != tc.appWant { |
| + t.Fatalf("the app saw %d requests, want %d", n, tc.appWant) |
| + } |
| + home, far := x.rows() |
| + if tc.admit { |
| + if x.a.calls.Load() != 1 || far.requests != 1+waiters || home.requests != 0 { |
| + t.Fatalf("home calls %d, metered home %+v far %+v; want one fill, every delivery at the far edge", |
| + x.a.calls.Load(), home, far) |
| + } |
| + return |
| + } |
| + // Each waiter reached the home on its own, as an ordinary hop the |
| + // home meters; the initiator's acknowledged fill is the far edge's. |
| + if x.a.calls.Load() != 1+waiters || far.requests != 1 || home.requests != waiters || home.hopRequests != waiters { |
| + t.Fatalf("home calls %d, metered home %+v far %+v; want each waiter forwarded and metered at the home", |
| + x.a.calls.Load(), home, far) |
| + } |
| + x.wantNothingStored(t, "a refused coalesced fill") |
| + }) |
| + } |
| +} |
| + |
| +func TestAssetE2EStalledBodyIsAbandoned(t *testing.T) { |
| + setFillDeadline(t, 500*time.Millisecond) |
| + unstall := make(chan struct{}) |
| + started := make(chan struct{}) |
| + var first atomic.Bool |
| + x := newAssetE2E(t, assetE2EOpts{handler: func(w http.ResponseWriter, r *http.Request) { |
| + if !first.CompareAndSwap(false, true) { |
| + assetOK(laBody)(w, r) |
| + return |
| + } |
| + 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 <-unstall: |
| + case <-r.Context().Done(): |
| + } |
| + io.WriteString(w, "-rest") |
| + }}) |
| + var once atomic.Bool |
| + free := func() { |
| + if once.CompareAndSwap(false, true) { |
| + close(unstall) |
| + } |
| + } |
| + t.Cleanup(free) |
| + |
| + res := x.fetchAsync(x.b, "/assets/app.js") |
| + <-started |
| + laWaitFor(t, "both edges' reservations", func() bool { |
| + return x.aStore.Stats().Reserved > 0 && x.bStore.Stats().Reserved > 0 |
| + }) |
| + laWaitFor(t, "both reservations to go back at the deadline", func() bool { |
| + return x.aStore.Stats().Reserved == 0 && x.bStore.Stats().Reserved == 0 |
| + }) |
| + select { |
| + case r := <-res: |
| + t.Fatalf("the client finished (%v) while the app was still stalled", r.err) |
| + default: |
| + } |
| + free() |
| + r := e2eAwait(t, res) |
| + wantE2ECache(t, r.resp, "miss") |
| + if r.body != "partial-rest" { |
| + t.Fatalf("the client got %q, want the whole stream as an ordinary response would", r.body) |
| + } |
| + x.wantNothingStored(t, "an abandoned fill") |
| +} |
| + |
| +// ---- generation-managed instances ------------------------------------------ |
| + |
| +// genAssetApp is one generation's process answering every path with body as |
| +// a cacheable script, counting the requests it answered. |
| +func genAssetApp(t *testing.T, sock, body string) (*genApp, *atomic.Int64) { |
| + t.Helper() |
| + var n atomic.Int64 |
| + a := startGenApp(t, sock, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + n.Add(1) |
| + assetOK(body)(w, r) |
| + })) |
| + return a, &n |
| +} |
| + |
| +// newGenAssetE2E is the scene with laHost an activator-managed instance on a |
| +// unix socket (Kind instance, Hibernate set: what selects generation |
| +// routing at the socket arm, drift D15), its generation v1 serving body |
| +// "v1" and v2 installed beside it, answering "v2". |
| +func newGenAssetE2E(t *testing.T) (x *assetE2E, act *genActivator, v1, v2 *genApp, n1, n2 *atomic.Int64) { |
| + t.Helper() |
| + dir := genSockDir(t) |
| + // The canonical socket answers loudly: a request reaching it means the |
| + // edge fell back to plain socket proxying. |
| + startGenApp(t, filepath.Join(dir, "canon.sock"), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + http.Error(w, "canonical", http.StatusInternalServerError) |
| + })) |
| + v1, n1 = genAssetApp(t, filepath.Join(dir, "v1.sock"), "v1") |
| + v2, n2 = genAssetApp(t, filepath.Join(dir, "v2.sock"), "v2") |
| + act = &genActivator{fakeGens: newFakeGens(true)} |
| + act.switchTo(laHost, GenInfo{Socket: v1.sock, N: 1, Build: "v1"}) |
| + x = newAssetE2E(t, assetE2EOpts{act: act, route: func(rt *registry.Route) { |
| + rt.Hibernate = true |
| + rt.Socket = filepath.Join(dir, "canon.sock") |
| + rt.Version = "v0" |
| + }}) |
| + // A fixture that silently fell back to plain proxying would test |
| + // nothing here (astra P2-4). |
| + up, ok := x.a.edge.lookupUpstreamPath(laHost, "/assets/app.js") |
| + if !ok || !up.genManaged || !up.hibernating { |
| + t.Fatalf("the home's upstream for %s is ok=%v genManaged=%v hibernating=%v, want a generation-managed instance", |
| + laHost, ok, up.genManaged, up.hibernating) |
| + } |
| + return x, act, v1, v2, n1, n2 |
| +} |
| + |
| +func (x *assetE2E) wantStoredNowhere(t *testing.T, path, what string) { |
| + t.Helper() |
| + for name, st := range map[string]*assetcache.Store{"home": x.aStore, "far": x.bStore} { |
| + if _, ok := st.Get(x.entryKey(path)); ok { |
| + t.Fatalf("%s: the %s store holds %s", what, name, path) |
| + } |
| + } |
| +} |
| + |
| +func TestAssetE2EUndeclaringBuildIsNotStored(t *testing.T) { |
| + t.Run("only the installed build declares", func(t *testing.T) { |
| + x, _, _, _, n1, n2 := newGenAssetE2E(t) |
| + x.local.declare("v1", false) |
| + x.local.declare("v2", true) |
| + for _, be := range []*backhaulEdge{x.b, x.a} { |
| + resp, body := x.fetch(t, be, "/assets/app.js") |
| + wantE2ECache(t, resp, "bypass") |
| + if body != "v1" { |
| + t.Fatalf("body = %q, want the serving build's fallback", body) |
| + } |
| + } |
| + x.wantStoredNowhere(t, "/assets/app.js", "the serving build declared nothing") |
| + if n1.Load() != 2 || n2.Load() != 0 { |
| + t.Fatalf("v1 answered %d and v2 %d requests, want v1 both", n1.Load(), n2.Load()) |
| + } |
| + }) |
| + t.Run("only the retiring build declares", func(t *testing.T) { |
| + x, act, _, v2, _, _ := newGenAssetE2E(t) |
| + x.local.declare("v1", true) |
| + x.local.declare("v2", false) |
| + // The control: while the declaring build serves, the fixture stores. |
| + resp, _ := x.fetch(t, x.b, "/assets/ctl.js") |
| + wantE2ECache(t, resp, "miss") |
| + for name, st := range map[string]*assetcache.Store{"home": x.aStore, "far": x.bStore} { |
| + if _, ok := st.Get(x.entryKey("/assets/ctl.js")); !ok { |
| + t.Fatalf("test bug: the declaring build's response was not stored on the %s edge", name) |
| + } |
| + } |
| + |
| + act.switchTo(laHost, GenInfo{Socket: v2.sock, N: 2, Build: "v2"}) |
| + for _, be := range []*backhaulEdge{x.b, x.a} { |
| + resp, body := x.fetch(t, be, "/assets/app.js") |
| + wantE2ECache(t, resp, "bypass") |
| + if body != "v2" { |
| + t.Fatalf("body = %q, want the installed build's answer", body) |
| + } |
| + } |
| + x.wantStoredNowhere(t, "/assets/app.js", "the installed build declared nothing") |
| + }) |
| +} |
| + |
| +// restartAssets is a box's edge process restarting with a warm disk: its |
| +// store reopened from the same directory, a fresh home map that has not read |
| +// anything yet, the route table reloaded, and the cache armed again. |
| +func (x *assetE2E) restartAssets(t *testing.T, be *backhaulEdge, dir string, local LocalAssets) *assetcache.Store { |
| + t.Helper() |
| + be.edge.stopAssetSweep() |
| + st := openStoreAt(t, dir) |
| + be.homes = be.edge.newHomeMap() |
| + be.edge.homes.Store(be.homes) |
| + if err := be.edge.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + armForTest(t, be.edge, st, local) |
| + return st |
| +} |
| + |
| +func TestAssetE2EWarmSleepRestart(t *testing.T) { |
| + x, act, v1, _, n1, _ := newGenAssetE2E(t) |
| + for _, want := range []string{"miss", "hit"} { |
| + for _, be := range []*backhaulEdge{x.a, x.b} { |
| + resp, body := x.fetch(t, be, "/assets/app.js") |
| + wantE2ECache(t, resp, want) |
| + if body != "v1" { |
| + t.Fatalf("body = %q", body) |
| + } |
| + } |
| + } |
| + if n := n1.Load(); n != 1 { |
| + t.Fatalf("the generation answered %d requests warming, want 1", n) |
| + } |
| + |
| + // Sleep: the activator takes the generation away and its process exits. |
| + act.sleep(laHost) |
| + v1.stop() |
| + served, asks := act.served.Load(), act.askCount() |
| + |
| + // Restart both edge processes on their warm disks. |
| + x.aStore = x.restartAssets(t, x.a, x.aDir, x.local) |
| + x.bStore = x.restartAssets(t, x.b, x.bDir, &fakeLocalAssets{hosts: map[string]HostAssets{}, builds: map[string]bool{}}) |
| + for name, st := range map[string]*assetcache.Store{"home": x.aStore, "far": x.bStore} { |
| + if s := st.Stats(); s.Entries != 1 { |
| + t.Fatalf("the %s store reopened with %+v, want the warm entry", name, s) |
| + } |
| + } |
| + // D13: before the far edge's first home-map read, no disk answer and |
| + // today's unresolved-host behaviour. |
| + calls := x.a.calls.Load() |
| + resp, _ := x.fetch(t, x.b, "/assets/app.js") |
| + if resp.StatusCode != http.StatusNotFound || resp.Header.Get(assetCacheHeader) != "" { |
| + t.Fatalf("before the first read the far edge answered %d (Carlos-Cache %q), want the unknown-host 404", |
| + resp.StatusCode, resp.Header.Get(assetCacheHeader)) |
| + } |
| + if got := x.a.calls.Load(); got != calls { |
| + t.Fatalf("the far edge reached the home %d time(s) before its first read", got-calls) |
| + } |
| + x.converge(t) |
| + |
| + for _, be := range []*backhaulEdge{x.a, x.b} { |
| + calls := x.a.calls.Load() |
| + resp, body := x.fetch(t, be, "/assets/app.js") |
| + wantE2ECache(t, resp, "hit") |
| + if body != "v1" { |
| + t.Fatalf("body = %q", body) |
| + } |
| + // The client's own request is the home edge's only one: the far |
| + // hit never crosses the hop. |
| + if want := map[bool]int64{true: 1, false: 0}[be == x.a]; x.a.calls.Load()-calls != want { |
| + t.Fatalf("the home edge saw %d request(s) for one hit, want %d", x.a.calls.Load()-calls, want) |
| + } |
| + } |
| + if act.served.Load() != served || act.askCount() != asks || n1.Load() != 1 { |
| + t.Fatalf("the activator was entered %d times and asked for a socket %d times after the sleep; want neither (no wake)", |
| + act.served.Load()-served, act.askCount()-asks) |
| + } |
| +} |
| + |
| +// ---- precedence, size, ownership ------------------------------------------- |
| + |
| +// The far edge has a route catch-all of its own that would serve the host, |
| +// but annie homes it exactly: the exact-remote branch catches it. The hit is |
| +// then answered by neither the catch-all's app nor the home, and dials |
| +// nothing (e2eDialCounter on the backhaul port once the warm-up is done). |
| +func TestAssetE2EFarCatchBehindALocalWildcard(t *testing.T) { |
| + wild := newLABackend(t, assetOK("the far box's own catch-all")) |
| + x := newAssetE2E(t, assetE2EOpts{handler: assetOK(laBody), farRoutes: []registry.Route{{ |
| + Host: "*.example.com", Kind: "service", Addr: wild.srv.Listener.Addr().String(), Status: "ready", |
| + }}}) |
| + if _, ok := x.b.edge.lookupUpstreamPath(laHost, "/assets/app.js"); !ok || x.b.edge.servesExactly(laHost) { |
| + t.Fatal("test bug: the far edge's catch-all must match the host, and not exactly") |
| + } |
| + resp, body := x.fetch(t, x.b, "/assets/app.js") |
| + wantE2ECache(t, resp, "miss") |
| + if body != laBody { |
| + t.Fatalf("miss body = %q, want the home's", body) |
| + } |
| + |
| + x.b.edge.backhaulTransport(x.aEIP).CloseIdleConnections() |
| + calls := x.a.calls.Load() |
| + _, dials := e2eDialCounter(t) |
| + resp, body = x.fetch(t, x.b, "/assets/app.js") |
| + wantE2ECache(t, resp, "hit") |
| + if body != laBody { |
| + t.Fatalf("hit body = %q", body) |
| + } |
| + if n := dials.Load(); n != 0 { |
| + t.Fatalf("the far hit dialled the backhaul port %d time(s)", n) |
| + } |
| + if got := x.a.calls.Load(); got != calls { |
| + t.Fatalf("the home edge saw %d request(s) for a far hit", got-calls) |
| + } |
| + if n := wild.n.Load(); n != 0 { |
| + t.Fatalf("the far box's catch-all app answered %d request(s) for a caught path", n) |
| + } |
| + if n := x.app.n.Load(); n != 1 { |
| + t.Fatalf("the home's app saw %d requests, want 1", n) |
| + } |
| +} |
| + |
| +func TestAssetE2EOversizedResponseIsStoredNowhere(t *testing.T) { |
| + big := strings.Repeat("x", 33<<20) |
| + x := newAssetE2E(t, assetE2EOpts{handler: func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/javascript") |
| + w.Header().Set("Cache-Control", "public, max-age=3600") |
| + if r.URL.Path == "/assets/sized.js" { |
| + w.Header().Set("Content-Length", strconv.Itoa(len(big))) |
| + } else { |
| + w.(http.Flusher).Flush() |
| + } |
| + io.WriteString(w, big) |
| + }}) |
| + for _, tc := range []struct{ path, cache string }{ |
| + // A declared length over the cap is refused at header time. |
| + {"/assets/sized.js", "bypass"}, |
| + // An unknown length is reserved at the cap and discarded past it, |
| + // after the header (miss) went out. |
| + {"/assets/unsized.js", "miss"}, |
| + } { |
| + t.Run(tc.path, func(t *testing.T) { |
| + resp, body := x.fetch(t, x.b, tc.path) |
| + wantE2ECache(t, resp, tc.cache) |
| + if resp.StatusCode != http.StatusOK || len(body) != len(big) { |
| + t.Fatalf("served %d with %d bytes, want the whole %d-byte body", resp.StatusCode, len(body), len(big)) |
| + } |
| + x.wantNothingStored(t, tc.path) |
| + if _, far := x.wantMeteredOnce(t, "far"); far.bytes != int64(len(big)) { |
| + t.Fatalf("the far edge metered %d bytes, want %d", far.bytes, len(big)) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The far edge's published view names a generation, then an owner, that the |
| +// home no longer holds (the home has moved on; its edges file has not been |
| +// republished yet). The fill's assertion fails at the home, so it is an |
| +// ordinary hop: no acknowledgement, metered once at the home, and nothing |
| +// stored under the key the far edge asked for, on either edge. The home's |
| +// own local catch still answers the hop, as it answers any request it |
| +// routes, under the home's current owner and generation. |
| +func TestAssetE2EGenerationOrOwnerMismatchGetsNoAck(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + edit func(*registry.Route) |
| + }{ |
| + {"generation", func(rt *registry.Route) { rt.AssetGen = e2eGen2 }}, |
| + {"owner", func(rt *registry.Route) { rt.App = "blog" }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + x := newAssetE2E(t, assetE2EOpts{handler: assetOK(laBody)}) |
| + x.setHome(t, tc.edit) |
| + if a, _ := x.b.homes.AssetsFor(laHost, time.Now()); a.Gen != laGen || a.App != "shop" { |
| + t.Fatalf("test bug: the far edge's view moved with the home: %+v", a) |
| + } |
| + resp, body := x.fetch(t, x.b, "/assets/app.js") |
| + wantE2ECache(t, resp, "bypass") |
| + if body != laBody { |
| + t.Fatalf("body = %q", body) |
| + } |
| + req, out := x.aTap.last() |
| + if req.Get(assetFillHeader) == "" { |
| + t.Fatal("test bug: the far edge sent no fill") |
| + } |
| + if out.Get(assetAckHeader) != "" || out.Get(assetExpiresHeader) != "" { |
| + t.Fatalf("the home acknowledged a fill it does not hold: %v", out) |
| + } |
| + home, _ := x.wantMeteredOnce(t, "home") |
| + if home.hopRequests != 1 { |
| + t.Fatalf("metered home %+v, want the one request as a hop", home) |
| + } |
| + x.wantStoredNowhere(t, "/assets/app.js", "the asserted key") |
| + if s := x.bStore.Stats(); s.Entries != 0 || s.Reserved != 0 { |
| + t.Fatalf("the far store holds %+v", s) |
| + } |
| + own := assetcache.Key{Account: x.route.Account, App: x.route.App, Gen: x.route.AssetGen, Host: laHost, Path: "/assets/app.js"} |
| + if _, ok := x.aStore.Get(own); !ok { |
| + t.Fatalf("the home's own catch did not answer the ordinary hop under its current key %+v", own) |
| + } |
| + }) |
| + } |
| +} |