edge: asset catch decision, key and fill coalescer
canonicalAssetPath refuses any path the decoder or path.Clean would change, assetPrefixMatch and assetKey carry the owner and generation, and assetFlight shares only an admitted entry among at most 32 waiters of 10 s each.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2 files changed,
+439
−0
internal/edge/assetcatch.go+151 −0internal/edge/assetcatch_test.go+288 −0
CI failed — run details
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go| new file mode 100644 |
| index 000000000..9a3b1573a |
| --- /dev/null |
| +++ b/internal/edge/assetcatch.go |
| @@ -0,0 +1,151 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "net/url" |
| + "path" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/assetcache" |
| +) |
| + |
| +// The catch decision, the cache key and the fill coalescer (edge asset cache |
| +// design §5.1, §5.3, §5.4). |
| + |
| +const ( |
| + // assetMaxWaiters is how many requests may wait on one fill (§5.3). |
| + assetMaxWaiters = 32 |
| +) |
| + |
| +// assetWaitTimeout is how long one request waits on someone else's fill |
| +// (§5.3). A variable only so a test can shorten it. |
| +var assetWaitTimeout = 10 * time.Second |
| + |
| +// canonicalAssetPath reports whether u's path is already canonical (§5.1): |
| +// the decoder preserved no percent-encoding (RawPath is empty) and the path |
| +// equals its own path.Clean with any trailing slash restored. A path that is |
| +// not canonical is never normalised into one: the key and the upstream |
| +// request would then describe a different URL from the one the client asked |
| +// for. |
| +func canonicalAssetPath(u *url.URL) bool { |
| + if u == nil || u.RawPath != "" || u.Path == "" || u.Path[0] != '/' { |
| + return false |
| + } |
| + c := path.Clean(u.Path) |
| + if strings.HasSuffix(u.Path, "/") && !strings.HasSuffix(c, "/") { |
| + c += "/" |
| + } |
| + return c == u.Path |
| +} |
| + |
| +// assetPrefixMatch reports whether p starts with any declared prefix. The |
| +// match is byte-wise, as the declaration grammar is (release.ValidAssetPaths: |
| +// every prefix starts and ends with "/"); an empty prefix matches nothing. |
| +func assetPrefixMatch(paths []string, p string) bool { |
| + for _, q := range paths { |
| + if q != "" && strings.HasPrefix(p, q) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// assetKey is the cache key (§5.4): the owner and generation the host's |
| +// asset answer published, the request host, and the request's path and raw |
| +// query exactly as received. The caller has checked canonicalAssetPath, so |
| +// nothing here is cleaned. |
| +func assetKey(a HostAssets, host string, u *url.URL) assetcache.Key { |
| + return assetcache.Key{ |
| + Account: a.Account, |
| + App: a.App, |
| + Gen: a.Gen, |
| + Host: host, |
| + Path: u.Path, |
| + RawQuery: u.RawQuery, |
| + } |
| +} |
| + |
| +// assetFlight coalesces concurrent fills of one key (§5.3). The first join |
| +// for an id leads: it makes the request and calls done with what it stored. |
| +// Every later join waits for that, and what it waits for is an admitted |
| +// entry, never a response, so a refused response reaches nobody but the |
| +// client it was made for: when the leader finishes with no entry, each |
| +// waiter's wait reports false and the waiter makes its own request. |
| +// |
| +// The zero value is ready to use. |
| +type assetFlight struct { |
| + mu sync.Mutex |
| + m map[string]*assetCall |
| +} |
| + |
| +type assetCall struct { |
| + waiters int // waiter slots held, guarded by assetFlight.mu |
| + fin chan struct{} |
| + entry *assetcache.Entry // set before fin closes |
| + once sync.Once |
| +} |
| + |
| +// noEntry is the wait of a leader and of a joiner refused at the cap. |
| +func noEntry(context.Context) (*assetcache.Entry, bool) { return nil, false } |
| + |
| +func noDone(*assetcache.Entry) {} |
| + |
| +// join registers interest in id. |
| +// |
| +// A leader (leader true) must call done exactly once when its fill has |
| +// settled, with the admitted entry or nil. done is idempotent. A leader's |
| +// wait returns false at once. |
| +// |
| +// Otherwise the caller is a waiter: it must call wait, which returns the |
| +// leader's entry and true, or false after assetWaitTimeout, when ctx ends, |
| +// or when the leader finishes with no entry. A waiter holds one of the |
| +// assetMaxWaiters slots from join until wait returns. The join over the cap |
| +// gets a wait that returns false at once and holds no slot; its done does |
| +// nothing. |
| +func (f *assetFlight) join(id string) (leader bool, wait func(ctx context.Context) (*assetcache.Entry, bool), done func(*assetcache.Entry)) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + c, open := f.m[id] |
| + if !open { |
| + if f.m == nil { |
| + f.m = make(map[string]*assetCall) |
| + } |
| + c = &assetCall{fin: make(chan struct{})} |
| + f.m[id] = c |
| + return true, noEntry, func(e *assetcache.Entry) { |
| + c.once.Do(func() { |
| + f.mu.Lock() |
| + if f.m[id] == c { |
| + delete(f.m, id) |
| + } |
| + f.mu.Unlock() |
| + c.entry = e |
| + close(c.fin) |
| + }) |
| + } |
| + } |
| + if c.waiters >= assetMaxWaiters { |
| + return false, noEntry, noDone |
| + } |
| + c.waiters++ |
| + var left sync.Once |
| + return false, func(ctx context.Context) (*assetcache.Entry, bool) { |
| + defer left.Do(func() { |
| + f.mu.Lock() |
| + c.waiters-- |
| + f.mu.Unlock() |
| + }) |
| + t := time.NewTimer(assetWaitTimeout) |
| + defer t.Stop() |
| + select { |
| + case <-c.fin: |
| + return c.entry, c.entry != nil |
| + case <-ctx.Done(): |
| + return nil, false |
| + case <-t.C: |
| + return nil, false |
| + } |
| + }, noDone |
| +} |
diff --git a/internal/edge/assetcatch_test.go b/internal/edge/assetcatch_test.go| new file mode 100644 |
| index 000000000..0aeac17b7 |
| --- /dev/null |
| +++ b/internal/edge/assetcatch_test.go |
| @@ -0,0 +1,288 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "net/url" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/assetcache" |
| +) |
| + |
| +func TestCanonicalAssetPathTable(t *testing.T) { |
| + cases := []struct { |
| + raw string |
| + want bool |
| + }{ |
| + {"/assets/app.js", true}, |
| + {"/assets/dir/", true}, |
| + {"/assets/", true}, |
| + {"/assets/app.js?v=2", true}, |
| + {"/assets//app.js", false}, |
| + {"/assets/./app.js", false}, |
| + {"/assets/.", false}, |
| + {"/assets/../x", false}, |
| + {"/assets/dir/..", false}, |
| + {"/assets/%61pp.js", false}, |
| + {"/assets/a%2Fb.js", false}, |
| + {"/assets/dir//", false}, |
| + } |
| + for _, c := range cases { |
| + u, err := url.ParseRequestURI(c.raw) |
| + if err != nil { |
| + t.Fatalf("%q: %v", c.raw, err) |
| + } |
| + if got := canonicalAssetPath(u); got != c.want { |
| + t.Errorf("canonicalAssetPath(%q) = %v, want %v (Path %q RawPath %q)", c.raw, got, c.want, u.Path, u.RawPath) |
| + } |
| + } |
| + // Paths no request line produces: built by hand. |
| + for _, p := range []string{"", "assets/app.js"} { |
| + if canonicalAssetPath(&url.URL{Path: p}) { |
| + t.Errorf("canonicalAssetPath(Path %q) = true, want false", p) |
| + } |
| + } |
| + if canonicalAssetPath(nil) { |
| + t.Error("nil URL must not be canonical") |
| + } |
| +} |
| + |
| +func TestAssetPrefixMatch(t *testing.T) { |
| + paths := []string{"/assets/", "/_app/immutable/"} |
| + for p, want := range map[string]bool{ |
| + "/assets/app.js": true, |
| + "/assets/": true, |
| + "/_app/immutable/x/y.js": true, |
| + "/assets": false, |
| + "/assetsx/app.js": false, |
| + "/Assets/app.js": false, |
| + "/other/assets/app.js": false, |
| + "/": false, |
| + "": false, |
| + } { |
| + if got := assetPrefixMatch(paths, p); got != want { |
| + t.Errorf("assetPrefixMatch(%q) = %v, want %v", p, got, want) |
| + } |
| + } |
| + if assetPrefixMatch(nil, "/assets/app.js") { |
| + t.Error("no declared paths must match nothing") |
| + } |
| + if assetPrefixMatch([]string{""}, "/assets/app.js") { |
| + t.Error("an empty prefix must match nothing") |
| + } |
| +} |
| + |
| +func TestAssetKeyCarriesOwnerAndGen(t *testing.T) { |
| + u, _ := url.ParseRequestURI("/assets/app.js?v=2") |
| + base := HostAssets{Account: "acct", App: "shop", Gen: "g1", Paths: []string{"/assets/"}} |
| + k := assetKey(base, "shop.example.com", u) |
| + want := assetcache.Key{Account: "acct", App: "shop", Gen: "g1", Host: "shop.example.com", Path: "/assets/app.js", RawQuery: "v=2"} |
| + if k != want { |
| + t.Fatalf("key = %+v, want %+v", k, want) |
| + } |
| + id := k.ID() |
| + |
| + other := base |
| + other.Gen = "g2" |
| + if assetKey(other, "shop.example.com", u).ID() == id { |
| + t.Error("a different gen must change the ID") |
| + } |
| + other = base |
| + other.App = "blog" |
| + if assetKey(other, "shop.example.com", u).ID() == id { |
| + t.Error("a different app must change the ID") |
| + } |
| + other = base |
| + other.Account = "acct2" |
| + if assetKey(other, "shop.example.com", u).ID() == id { |
| + t.Error("a different account must change the ID") |
| + } |
| + if assetKey(base, "other.example.com", u).ID() == id { |
| + t.Error("a different host must change the ID") |
| + } |
| + u3, _ := url.ParseRequestURI("/assets/app.js?v=3") |
| + if assetKey(base, "shop.example.com", u3).ID() == id { |
| + t.Error("a different raw query must change the ID") |
| + } |
| + if assetKey(base, "shop.example.com", u).ID() != id { |
| + t.Error("the same inputs must give the same ID") |
| + } |
| +} |
| + |
| +func TestFlightSharesOnlyAnEntry(t *testing.T) { |
| + var f assetFlight |
| + leader, _, done := f.join("k") |
| + if !leader { |
| + t.Fatal("first join must lead") |
| + } |
| + const n = 5 |
| + var wg sync.WaitGroup |
| + got := make([]bool, n) |
| + ents := make([]*assetcache.Entry, n) |
| + for i := 0; i < n; i++ { |
| + l, wait, _ := f.join("k") |
| + if l { |
| + t.Fatalf("join %d led while a flight was open", i) |
| + } |
| + wg.Add(1) |
| + go func(i int) { |
| + defer wg.Done() |
| + ents[i], got[i] = wait(context.Background()) |
| + }(i) |
| + } |
| + done(nil) |
| + wg.Wait() |
| + for i := range got { |
| + if got[i] || ents[i] != nil { |
| + t.Errorf("waiter %d got (%v, %v) after a leader with no entry", i, ents[i], got[i]) |
| + } |
| + } |
| + |
| + // With an entry, every waiter gets that entry. |
| + leader, _, done = f.join("k") |
| + if !leader { |
| + t.Fatal("a finished flight must be forgotten: the next join leads") |
| + } |
| + e := &assetcache.Entry{} |
| + var waits []func(context.Context) (*assetcache.Entry, bool) |
| + for i := 0; i < n; i++ { |
| + _, w, _ := f.join("k") |
| + waits = append(waits, w) |
| + } |
| + done(e) |
| + for i, w := range waits { |
| + if g, ok := w(context.Background()); !ok || g != e { |
| + t.Errorf("waiter %d: (%p, %v), want the shared entry", i, g, ok) |
| + } |
| + } |
| + // done is idempotent. |
| + done(nil) |
| +} |
| + |
| +func TestFlightIdsAreIndependent(t *testing.T) { |
| + var f assetFlight |
| + a, _, da := f.join("a") |
| + b, _, db := f.join("b") |
| + defer da(nil) |
| + defer db(nil) |
| + if !a || !b { |
| + t.Fatal("different ids must each lead") |
| + } |
| +} |
| + |
| +func TestFlightCapsWaiters(t *testing.T) { |
| + if assetMaxWaiters != 32 { |
| + t.Fatalf("assetMaxWaiters = %d, want 32", assetMaxWaiters) |
| + } |
| + var f assetFlight |
| + _, _, done := f.join("k") |
| + var waits []func(context.Context) (*assetcache.Entry, bool) |
| + for i := 0; i < assetMaxWaiters; i++ { |
| + l, w, _ := f.join("k") |
| + if l { |
| + t.Fatalf("waiter %d led", i) |
| + } |
| + waits = append(waits, w) |
| + } |
| + l, over, overDone := f.join("k") |
| + if l { |
| + t.Fatal("the 33rd join must not lead") |
| + } |
| + start := time.Now() |
| + if e, ok := over(context.Background()); ok || e != nil { |
| + t.Fatalf("the 33rd waiter got (%v, %v), want false", e, ok) |
| + } |
| + if time.Since(start) > time.Second { |
| + t.Fatal("the 33rd waiter must return at once") |
| + } |
| + overDone(&assetcache.Entry{}) // a refused joiner's done must not finish the flight |
| + e := &assetcache.Entry{} |
| + done(e) |
| + for i, w := range waits { |
| + if g, ok := w(context.Background()); !ok || g != e { |
| + t.Errorf("admitted waiter %d lost the entry", i) |
| + } |
| + } |
| +} |
| + |
| +func TestFlightWaiterSlotFreesWhenItLeaves(t *testing.T) { |
| + var f assetFlight |
| + _, _, done := f.join("k") |
| + defer done(nil) |
| + old := assetWaitTimeout |
| + assetWaitTimeout = 5 * time.Millisecond |
| + t.Cleanup(func() { assetWaitTimeout = old }) |
| + for i := 0; i < 3*assetMaxWaiters; i++ { |
| + l, w, _ := f.join("k") |
| + if l { |
| + t.Fatal("led") |
| + } |
| + if _, ok := w(context.Background()); ok { |
| + t.Fatal("no entry yet") |
| + } |
| + } |
| + // Every one of those joined as a waiter (none was refused for the cap): |
| + // a refused joiner returns at once, an admitted one waits out the timeout. |
| + // Count by timing is flaky, so check the slot count directly. |
| + f.mu.Lock() |
| + c := f.m["k"] |
| + n := c.waiters |
| + f.mu.Unlock() |
| + if n != 0 { |
| + t.Fatalf("%d waiter slots still held after every waiter left", n) |
| + } |
| +} |
| + |
| +func TestFlightWaitTimesOut(t *testing.T) { |
| + if assetWaitTimeout != 10*time.Second { |
| + t.Fatalf("assetWaitTimeout = %v, want 10s", assetWaitTimeout) |
| + } |
| + old := assetWaitTimeout |
| + assetWaitTimeout = 30 * time.Millisecond |
| + t.Cleanup(func() { assetWaitTimeout = old }) |
| + |
| + var f assetFlight |
| + _, _, done := f.join("k") |
| + defer done(nil) |
| + _, wait, _ := f.join("k") |
| + start := time.Now() |
| + e, ok := wait(context.Background()) |
| + if ok || e != nil { |
| + t.Fatalf("timed-out wait got (%v, %v)", e, ok) |
| + } |
| + if d := time.Since(start); d < 20*time.Millisecond || d > 2*time.Second { |
| + t.Fatalf("wait returned after %v, want about 30ms", d) |
| + } |
| +} |
| + |
| +func TestFlightWaitEndsWithContext(t *testing.T) { |
| + var f assetFlight |
| + _, _, done := f.join("k") |
| + defer done(nil) |
| + _, wait, _ := f.join("k") |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + res := make(chan bool, 1) |
| + go func() { _, ok := wait(ctx); res <- ok }() |
| + cancel() |
| + select { |
| + case ok := <-res: |
| + if ok { |
| + t.Fatal("a cancelled wait must report false") |
| + } |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("wait ignored its context") |
| + } |
| +} |
| + |
| +func TestFlightLeaderWaitIsFalse(t *testing.T) { |
| + var f assetFlight |
| + l, wait, done := f.join("k") |
| + defer done(nil) |
| + if !l { |
| + t.Fatal("must lead") |
| + } |
| + if e, ok := wait(context.Background()); ok || e != nil { |
| + t.Fatal("the leader's own wait must report false") |
| + } |
| +} |