edge, host: slow a plan-throttled account and close its upgrades (plans 4c)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+340
−1
internal/edge/edge.go+19 −1internal/edge/planthrottle.go+113 −0internal/edge/planthrottle_test.go+149 −0internal/host/agent.go+10 −0internal/host/plans_pass.go+27 −0internal/host/plans_throttle_test.go+22 −0
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index c7ffc02d2..061bb5f20 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -57,6 +57,7 @@ import ( |
| "github.com/carlosframework/platform/internal/geo" |
| "github.com/carlosframework/platform/internal/geoip" |
| "github.com/carlosframework/platform/internal/lbhealth" |
| + "github.com/carlosframework/platform/internal/plans" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/ratelimit" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -320,6 +321,13 @@ type Edge struct { |
| rateMode RateMode |
| rateLimiter *ratelimit.Limiter |
| rateCeiling atomic.Pointer[func(registry.Route) ratelimit.Ceiling] |
| + // planThrottle, planLimiter and upgrades are the plan throttle (plans |
| + // 4c, planthrottle.go): the hook, the per-account buckets, and each |
| + // account's open upgraded connections, closable when it is throttled. |
| + planThrottle atomic.Pointer[func(registry.Route) (plans.Throttle, bool)] |
| + planLimiter *ratelimit.Limiter |
| + upgradesMu sync.Mutex |
| + upgrades map[string]map[*int]context.CancelFunc |
| } |
| // RunOption configures the Edge that Run/RunWithActivator* builds, before it |
| @@ -420,7 +428,8 @@ type upstream struct { |
| // (no hibernation). |
| func New(reg *registry.Registry, act Activator) (*Edge, error) { |
| e := &Edge{reg: reg, act: act, gate: gate.New(), probers: newProberSet(), gzipOn: gzipEnabled(), steeringHost: steeringProbeHostFromEnv(), appsDomain: appsDomainFromEnv(), |
| - lbHealth: lbHealthFromEnv(os.Getenv, act), rateMode: rateModeFromEnv(), rateLimiter: ratelimit.NewLimiter(time.Now, 100_000)} |
| + lbHealth: lbHealthFromEnv(os.Getenv, act), rateMode: rateModeFromEnv(), rateLimiter: ratelimit.NewLimiter(time.Now, 100_000), |
| + planLimiter: ratelimit.NewLimiter(time.Now, 100_000)} |
| e.geo = geo.NewSwappable() |
| e.geoLookup = e.geo.Lookup |
| // Generations (zero-downtime spec §7.2), before the startup Reload so |
| @@ -1775,6 +1784,12 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // proxy's hijack on a 101, so an open WebSocket is not counted, and |
| // it is itself an http.Hijacker (with Unwrap) for the proxy. A |
| // refusal is written to the raw writer. |
| + if !e.planUpgradeAdmit(w, r, up) { |
| + return |
| + } |
| + var untrack func() |
| + r, untrack = e.trackUpgrade(r, up) |
| + defer untrack() |
| release, ok := e.rateAdmit(w, r, up) |
| if !ok { |
| return |
| @@ -1853,6 +1868,9 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // the defer covers an answer that never wrote anything. A request that |
| // holds no slot (off, exempt, not an instance) keeps its writer as it |
| // was. |
| + if !e.planThrottleAdmit(w, r, up) { |
| + return |
| + } |
| release, admitted := e.rateAdmit(w, r, up) |
| if !admitted { |
| return |
diff --git a/internal/edge/planthrottle.go b/internal/edge/planthrottle.go| new file mode 100644 |
| index 000000000..5b3b031d9 |
| --- /dev/null |
| +++ b/internal/edge/planthrottle.go |
| @@ -0,0 +1,113 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/netip" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/ratelimit" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// planThrottleBucket is the one client key of an account's throttle bucket: |
| +// the bucket is the account's, whoever is asking. |
| +var planThrottleBucket = netip.MustParsePrefix("0.0.0.0/0") |
| + |
| +// SetPlanThrottleFor installs the plan throttle hook (plans 4c): whether a |
| +// route's account is slowed down for the rest of the month, and why |
| +// (internal/host's planThrottleFor). nil, the default and every box without |
| +// a plan catalog, throttles nothing. Safe to call while serving. |
| +func (e *Edge) SetPlanThrottleFor(f func(registry.Route) (plans.Throttle, bool)) { |
| + if f == nil { |
| + e.planThrottle.Store(nil) |
| + return |
| + } |
| + e.planThrottle.Store(&f) |
| +} |
| + |
| +// planThrottleOf is the route's throttle when one applies to this request. |
| +// Door, hop-door and tunnel callers are exempt, as from the rate limit. |
| +func (e *Edge) planThrottleOf(r *http.Request, up upstream) (plans.Throttle, bool) { |
| + f := e.planThrottle.Load() |
| + if f == nil || up.route.Kind != "instance" { |
| + return plans.Throttle{}, false |
| + } |
| + if _, door := doorCallerFrom(r.Context()); door || hopDoorFrom(r.Context()) || fromTunnel(r.Context()) { |
| + return plans.Throttle{}, false |
| + } |
| + return (*f)(up.route) |
| +} |
| + |
| +// planThrottleAdmit spends one token of a throttled account's shared |
| +// bucket. It is a plan stage, not abuse protection, so it refuses whatever |
| +// CARLOS_RATE_LIMIT says. When ok is false the 429 is written. |
| +func (e *Edge) planThrottleAdmit(w http.ResponseWriter, r *http.Request, up upstream) bool { |
| + if _, on := e.planThrottleOf(r, up); !on { |
| + return true |
| + } |
| + eff := ratelimit.Effective{Base: plans.ThrottleRule} |
| + _, d, retryAfter := e.planLimiter.Admit("plan:"+release.RouteAccount(up.route), eff, planThrottleBucket, "", false, false) |
| + if d == ratelimit.Allow { |
| + return true |
| + } |
| + e.logThrottled("plan-throttle "+up.route.Host, "plan throttle: refused a request for "+up.route.Host+" (the account is slowed down until the month ends)") |
| + writeRateLimited(w, retryAfter) |
| + return false |
| +} |
| + |
| +// planUpgradeAdmit is planThrottleAdmit for an upgrade: an awake-throttled |
| +// account opens no new connection that would hold its apps awake. |
| +func (e *Edge) planUpgradeAdmit(w http.ResponseWriter, r *http.Request, up upstream) bool { |
| + if th, on := e.planThrottleOf(r, up); on && th.Awake { |
| + e.logThrottled("plan-throttle-upgrade "+up.route.Host, "plan throttle: refused an upgrade for "+up.route.Host) |
| + writeRateLimited(w, 60e9) |
| + return false |
| + } |
| + return e.planThrottleAdmit(w, r, up) |
| +} |
| + |
| +// trackUpgrade makes an upgrade's connection closable by its account |
| +// (CloseAccountUpgrades): the proxy ends an upgraded connection when its |
| +// request context is done. Only with a throttle hook armed, so a box |
| +// without plans keeps its request exactly as it was. |
| +func (e *Edge) trackUpgrade(r *http.Request, up upstream) (*http.Request, func()) { |
| + if e.planThrottle.Load() == nil || up.route.Kind != "instance" { |
| + return r, func() {} |
| + } |
| + acct := release.RouteAccount(up.route) |
| + ctx, cancel := context.WithCancel(r.Context()) |
| + h := new(int) |
| + e.upgradesMu.Lock() |
| + if e.upgrades == nil { |
| + e.upgrades = map[string]map[*int]context.CancelFunc{} |
| + } |
| + if e.upgrades[acct] == nil { |
| + e.upgrades[acct] = map[*int]context.CancelFunc{} |
| + } |
| + e.upgrades[acct][h] = cancel |
| + e.upgradesMu.Unlock() |
| + return r.WithContext(ctx), func() { |
| + e.upgradesMu.Lock() |
| + delete(e.upgrades[acct], h) |
| + if len(e.upgrades[acct]) == 0 { |
| + delete(e.upgrades, acct) |
| + } |
| + e.upgradesMu.Unlock() |
| + cancel() |
| + } |
| +} |
| + |
| +// CloseAccountUpgrades ends every open upgraded connection of the account's |
| +// routes, and says how many (plans 4c: an account becomes awake-throttled). |
| +func (e *Edge) CloseAccountUpgrades(account string) int { |
| + e.upgradesMu.Lock() |
| + cancels := e.upgrades[account] |
| + delete(e.upgrades, account) |
| + e.upgradesMu.Unlock() |
| + for _, cancel := range cancels { |
| + cancel() |
| + } |
| + return len(cancels) |
| +} |
diff --git a/internal/edge/planthrottle_test.go b/internal/edge/planthrottle_test.go| new file mode 100644 |
| index 000000000..73af892d0 |
| --- /dev/null |
| +++ b/internal/edge/planthrottle_test.go |
| @@ -0,0 +1,149 @@ |
| +package edge |
| + |
| +import ( |
| + "bufio" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/ratelimit" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +const ( |
| + ptHost = "throttled.example" |
| + ptOtherHost = "other.example" |
| +) |
| + |
| +// throttleScene: two instances of two accounts behind one edge, the plan |
| +// throttle hook answering from on/awake for bdk, and a frozen clock for |
| +// the throttle's bucket so the rule is exact. |
| +func throttleScene(t *testing.T, on, awake *atomic.Bool, backend string) *rateScene { |
| + t.Helper() |
| + s := newRateScene(t, "", nil, |
| + registry.Route{Host: ptHost, Kind: "instance", Addr: backend, Status: "ready", App: "web", Account: "bdk"}, |
| + registry.Route{Host: ptOtherHost, Kind: "instance", Addr: backend, Status: "ready", App: "shop", Account: "bdm"}, |
| + ) |
| + frozen := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC) |
| + s.e.planLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000) |
| + s.e.SetPlanThrottleFor(func(rt registry.Route) (plans.Throttle, bool) { |
| + if rt.Account != "bdk" || !on.Load() { |
| + return plans.Throttle{}, false |
| + } |
| + return plans.Throttle{Bandwidth: true, Awake: awake.Load(), Until: frozen.Add(time.Hour)}, true |
| + }) |
| + return s |
| +} |
| + |
| +func okBackend(t *testing.T) string { |
| + t.Helper() |
| + b := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok") })) |
| + t.Cleanup(b.Close) |
| + return b.Listener.Addr().String() |
| +} |
| + |
| +func TestThrottleRefusesPastTheRule(t *testing.T) { |
| + var on, awake atomic.Bool |
| + on.Store(true) |
| + s := throttleScene(t, &on, &awake, okBackend(t)) |
| + for i := 0; i < plans.ThrottleRule.Burst; i++ { |
| + wantOK(t, s.get(t, "203.0.113.1", ptHost, "/"), fmt.Sprintf("request %d within the burst", i)) |
| + } |
| + res := s.get(t, "203.0.113.9", ptHost, "/") // another client: the bucket is the account's |
| + if res.status != http.StatusTooManyRequests || res.header.Get("Retry-After") == "" || res.header.Get("Cache-Control") != "no-store" { |
| + t.Fatalf("past the throttle: %d %v, want a 429 with Retry-After and no-store (even in observe mode)", res.status, res.header) |
| + } |
| +} |
| + |
| +func TestThrottleIsPerAccount(t *testing.T) { |
| + var on, awake atomic.Bool |
| + on.Store(true) |
| + s := throttleScene(t, &on, &awake, okBackend(t)) |
| + for i := 0; i <= plans.ThrottleRule.Burst; i++ { |
| + s.get(t, "203.0.113.1", ptHost, "/") |
| + } |
| + for i := 0; i < 40; i++ { |
| + wantOK(t, s.get(t, "203.0.113.1", ptOtherHost, "/"), "another account's instance") |
| + } |
| +} |
| + |
| +func TestNoThrottleHookUnchanged(t *testing.T) { |
| + s := newRateScene(t, "", nil, registry.Route{Host: ptHost, Kind: "instance", Addr: okBackend(t), Status: "ready", App: "web", Account: "bdk"}) |
| + for i := 0; i < 60; i++ { |
| + wantOK(t, s.get(t, "203.0.113.1", ptHost, "/"), "no hook") |
| + } |
| +} |
| + |
| +// openSocket upgrades a raw connection to host and returns its reader. |
| +func openSocket(t *testing.T, s *rateScene, host string) (net.Conn, *bufio.Reader, int) { |
| + t.Helper() |
| + c, err := net.Dial("tcp", s.front.Listener.Addr().String()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { c.Close() }) |
| + c.SetDeadline(time.Now().Add(10 * time.Second)) |
| + fmt.Fprintf(c, "GET /socket HTTP/1.1\r\nHost: %s\r\n%s: 203.0.113.1\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", host, rlPeerHeader) |
| + br := bufio.NewReader(c) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil { |
| + t.Fatalf("handshake: %v", err) |
| + } |
| + return c, br, resp.StatusCode |
| +} |
| + |
| +func TestAwakeThrottleClosesAndRefusesUpgrades(t *testing.T) { |
| + ws := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/socket" { |
| + io.WriteString(w, "ok") |
| + return |
| + } |
| + conn, buf, err := w.(http.Hijacker).Hijack() |
| + if err != nil { |
| + return |
| + } |
| + defer conn.Close() |
| + buf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") |
| + buf.Flush() |
| + for { |
| + line, err := buf.ReadString('\n') |
| + if err != nil { |
| + return |
| + } |
| + buf.WriteString("echo:" + line) |
| + buf.Flush() |
| + } |
| + })) |
| + t.Cleanup(ws.Close) |
| + var on, awake atomic.Bool |
| + s := throttleScene(t, &on, &awake, ws.Listener.Addr().String()) |
| + |
| + c, br, status := openSocket(t, s, ptHost) |
| + if status != http.StatusSwitchingProtocols { |
| + t.Fatalf("handshake before the throttle = %d", status) |
| + } |
| + fmt.Fprint(c, "one\n") |
| + if line, err := br.ReadString('\n'); err != nil || line != "echo:one\n" { |
| + t.Fatalf("echo = %q, %v", line, err) |
| + } |
| + |
| + on.Store(true) |
| + awake.Store(true) |
| + if n := s.e.CloseAccountUpgrades("bdk"); n != 1 { |
| + t.Fatalf("CloseAccountUpgrades = %d, want 1", n) |
| + } |
| + fmt.Fprint(c, "two\n") |
| + if _, err := br.ReadString('\n'); err == nil { |
| + t.Fatal("the socket stayed open after the account was awake-throttled") |
| + } |
| + if _, _, status := openSocket(t, s, ptHost); status != http.StatusTooManyRequests { |
| + t.Fatalf("new upgrade while awake-throttled = %d, want 429", status) |
| + } |
| + wantOK(t, s.get(t, "203.0.113.1", ptHost, "/plain"), "a plain request while awake-throttled") |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 148e56557..d07a9acfd 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -944,6 +944,16 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // activator's idle hook reads, so a box without a plan catalog gets |
| // the zero Ceiling and no extra reads. |
| e.SetRateCeilingFor(planRateCeilingFor) |
| + // The plan throttle (plans 4c), from the same snapshot: a slowed |
| + // account's shared bucket, and its open upgrades closed when it |
| + // becomes awake-throttled. |
| + e.SetPlanThrottleFor(planThrottleFor) |
| + closeUpgrades := func(sqid string) { |
| + if n := e.CloseAccountUpgrades(sqid); n > 0 { |
| + log.Printf("agent: plan throttle: closed %d open connection(s) of account %s", n, sqid) |
| + } |
| + } |
| + planAwakeThrottled.Store(&closeUpgrades) |
| // Same arming point as the meter: the edge observes an upstream 5xx |
| // on the serving path and files it here (spec 2026-09-07 §3.2), and |
| // errshipLoop above ships what this fills. Guarded, because a typed |
diff --git a/internal/host/plans_pass.go b/internal/host/plans_pass.go| index c3f5986f3..b05b93acd 100644 |
| --- a/internal/host/plans_pass.go |
| +++ b/internal/host/plans_pass.go |
| @@ -126,6 +126,33 @@ func plansPass(ctx context.Context, s release.Store, reg *registry.Registry, get |
| if !failed { |
| planLimitsFailures.Store(0) |
| } |
| + notifyAwakeThrottled(prev, next) |
| +} |
| + |
| +// planAwakeThrottled is told each account that has just become |
| +// awake-throttled, so the edge can close its open upgrades (plans 4c). |
| +// Armed by the agent with the edge; nil does nothing. |
| +var planAwakeThrottled atomic.Pointer[func(sqid string)] |
| + |
| +// notifyAwakeThrottled calls planAwakeThrottled for each account whose |
| +// awake throttle is in force in next and was not in prev. |
| +func notifyAwakeThrottled(prev, next *planLimitsSnapshot) { |
| + f := planAwakeThrottled.Load() |
| + if f == nil || next == nil { |
| + return |
| + } |
| + now := time.Now() |
| + for sqid, th := range next.throttle { |
| + if !th.Awake || !th.Active(now) { |
| + continue |
| + } |
| + if prev != nil { |
| + if was, ok := prev.throttle[sqid]; ok && was.Awake && was.Active(now) { |
| + continue |
| + } |
| + } |
| + (*f)(sqid) |
| + } |
| } |
| // planLimitsFailed logs the first failure of a run and every tenth after it. |
diff --git a/internal/host/plans_throttle_test.go b/internal/host/plans_throttle_test.go| index 2201dda2b..559063916 100644 |
| --- a/internal/host/plans_throttle_test.go |
| +++ b/internal/host/plans_throttle_test.go |
| @@ -90,3 +90,25 @@ func TestThrottleOffWithPlanLimitsOff(t *testing.T) { |
| t.Fatal("throttled with CARLOS_PLAN_LIMITS=off") |
| } |
| } |
| + |
| +// An account that becomes awake-throttled has its open upgrades closed, |
| +// once, on the pass that sees it first. |
| +func TestPlansPassClosesUpgradesWhenAwakeThrottled(t *testing.T) { |
| + s, reg := plansWorld(t) |
| + var closed []string |
| + f := func(sqid string) { closed = append(closed, sqid) } |
| + planAwakeThrottled.Store(&f) |
| + t.Cleanup(func() { planAwakeThrottled.Store(nil) }) |
| + putMarker(t, s, true) |
| + putThrottledLimits(t, s, "bab", &plans.Throttle{Bandwidth: true, Until: time.Now().Add(time.Hour)}) |
| + plansPass(context.Background(), s, reg, plansNoEnv) |
| + if len(closed) != 0 { |
| + t.Fatalf("a bandwidth-only throttle closed upgrades: %v", closed) |
| + } |
| + putThrottledLimits(t, s, "bab", &plans.Throttle{Awake: true, Until: time.Now().Add(time.Hour)}) |
| + plansPass(context.Background(), s, reg, plansNoEnv) |
| + plansPass(context.Background(), s, reg, plansNoEnv) |
| + if len(closed) != 1 || closed[0] != "bab" { |
| + t.Fatalf("closed = %v, want bab once", closed) |
| + } |
| +} |