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