carlos / platform Public

edge: take the backhaul stream slot at the 101, not from the request

Review round 1 (#1535). The Upgrade header is the client's to send, so it
must not buy a request out of the request pool. Every hop is admitted on
a request slot; when the home answers 101 the hop takes a stream slot
(stream share, same client key) and gives the request slot back, before
the proxy hijacks. A stream pool with no room fails the hop there: the
backend connection is closed and the client gets 503 + Retry-After 2
(site backhaul-streams-busy) or the 429, counted as a stream or share
shed. A non-101 answer keeps its request slot to the end. The far asset
fill is back to plain backhaulAdmit, and backhaulUpgrade is gone.

Defaults are 128 request slots and 512 stream slots, with the per-socket
cost and containment argument in the doc. Each pool's share is
min(constant, max(1, cap/4)), so a lowered cap keeps a fair share.
Journal lines lose their em dashes. Adds a barrier-coordinated
contention test over both pools.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b2a9de88fd04df5883c8083e9590a7d1e5f0ff34 parent 9ac6ad3
4 files changed, +523 −276
  • internal/edge/assetcatch.go +1 −4
  • internal/edge/backhaul_holder_export_test.go +1 −5
  • internal/edge/backhaul_streams_test.go +384 −193
  • internal/edge/edge.go +137 −74
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go
index ad8bfd281..1b356fcb7 100644
--- a/internal/edge/assetcatch.go
+++ b/internal/edge/assetcatch.go
@@ -1290,10 +1290,7 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string
forward()
return true
}
- // A fill is a plain GET the edge builds from an allow-list
- // (assetFillRequest), never an upgrade, whatever the client's own
- // headers say: it takes a request-pool slot.
- releaseSlot, ok := e.backhaulAdmitPool(cw, r, eip, box, false)
+ releaseSlot, ok := e.backhaulAdmit(cw, r, eip, box)
if !ok {
done(nil)
return true
diff --git a/internal/edge/backhaul_holder_export_test.go b/internal/edge/backhaul_holder_export_test.go
index 1686338dd..b80ea17cb 100644
--- a/internal/edge/backhaul_holder_export_test.go
+++ b/internal/edge/backhaul_holder_export_test.go
@@ -170,13 +170,9 @@ func (s *BackhaulHolderScene) Upgrade(t *testing.T) {
if resp.StatusCode != 101 {
t.Fatalf("upgrade: %d", resp.StatusCode)
}
- // An upgrade takes its slots from the stream pool (#1535).
- if v, ok := s.sender.edge.backhaulStreamInflight.Load("annie"); !ok || v.(*atomic.Int64).Load() != 0 {
+ if v, ok := s.sender.edge.backhaulInflight.Load("annie"); !ok || v.(*atomic.Int64).Load() != 0 {
t.Fatal("completed first hop retained its capacity slot during the upgrade")
}
- if v, ok := s.sender.edge.backhaulInflight.Load("annie"); ok && v.(*atomic.Int64).Load() != 0 {
- t.Fatal("an upgrade took a request-pool slot")
- }
fmt.Fprint(c, "ping\n")
if line, err := br.ReadString('\n'); err != nil || line != "holder:ping\n" {
t.Fatalf("echo=%q %v", line, err)
diff --git a/internal/edge/backhaul_streams_test.go b/internal/edge/backhaul_streams_test.go
index f699fad1c..728cd7629 100644
--- a/internal/edge/backhaul_streams_test.go
+++ b/internal/edge/backhaul_streams_test.go
@@ -1,13 +1,14 @@
package edge
-// Two pools per destination box (#1535): an upgrade request (a WebSocket)
-// holds its slot for the life of the socket, so upgraded hops take theirs
-// from a stream pool of their own and can never fill the request pool that
-// ordinary request/response hops share.
+// Two pools per destination box (#1535): an upgraded hop (a WebSocket) holds
+// its slot for the life of the socket, so a hop the home answers with 101
+// moves from the request pool to a stream pool of its own, and open sockets
+// can never fill the request pool that ordinary hops share.
import (
"bufio"
"context"
+ "errors"
"fmt"
"io"
"net"
@@ -38,53 +39,42 @@ func poolCount(m *sync.Map, box string) int64 {
return v.(*atomic.Int64).Load()
}
-func upgradeReq(conn ...string) *http.Request {
- r := httptest.NewRequest(http.MethodGet, "http://example.com/cable", nil)
- for _, c := range conn {
- r.Header.Add("Connection", c)
+// The defaults, and the share scaled to a quarter of a small cap.
+func TestBackhaulPoolDefaults(t *testing.T) {
+ if defaultBackhaulMaxInflight != 128 {
+ t.Fatalf("defaultBackhaulMaxInflight = %d, want 128", defaultBackhaulMaxInflight)
+ }
+ if defaultBackhaulMaxStreams != 512 {
+ t.Fatalf("defaultBackhaulMaxStreams = %d, want 512", defaultBackhaulMaxStreams)
+ }
+ if backhaulClientShare != 8 || backhaulStreamClientShare != 64 {
+ t.Fatalf("shares = %d, %d, want 8, 64", backhaulClientShare, backhaulStreamClientShare)
}
- return r
-}
-
-func TestBackhaulUpgradeClassification(t *testing.T) {
for _, tc := range []struct {
- name string
- conn []string
- upgrade []string
- want bool
+ share int
+ limit int64
+ want int
}{
- {"websocket", []string{"Upgrade"}, []string{"websocket"}, true},
- {"keep-alive and upgrade", []string{"keep-alive, Upgrade"}, []string{"websocket"}, true},
- {"case-insensitive token", []string{"KEEP-ALIVE, uPgRaDe"}, []string{"WebSocket"}, true},
- {"token on a second Connection line", []string{"keep-alive", "upgrade"}, []string{"websocket"}, true},
- {"missing Upgrade header", []string{"Upgrade"}, nil, false},
- {"blank Upgrade header", []string{"Upgrade"}, []string{" "}, false},
- {"Upgrade without the Connection token", nil, []string{"websocket"}, false},
- {"keep-alive only", []string{"keep-alive"}, []string{"websocket"}, false},
- {"upgrade only as part of a longer token", []string{"upgraded"}, []string{"websocket"}, false},
- {"plain GET", nil, nil, false},
+ {8, defaultBackhaulMaxInflight, 8},
+ {64, defaultBackhaulMaxStreams, 64},
+ {8, 64, 8},
+ {64, 100, 25},
+ {64, 8, 2},
+ {8, 8, 2},
+ {64, 3, 1},
+ {8, 1, 1},
+ {8, 0, 1},
} {
- r := upgradeReq(tc.conn...)
- for _, u := range tc.upgrade {
- r.Header.Add("Upgrade", u)
- }
- if got := backhaulUpgrade(r); got != tc.want {
- t.Errorf("%s: backhaulUpgrade = %v, want %v (Connection %q, Upgrade %q)", tc.name, got, tc.want, tc.conn, tc.upgrade)
+ if got := backhaulShare(tc.share, tc.limit); got != tc.want {
+ t.Errorf("backhaulShare(%d, %d) = %d, want %d", tc.share, tc.limit, got, tc.want)
}
}
-}
-
-// The defaults: the request pool no longer holds parked sockets, so it is
-// raised from 64 to 256; the stream pool is 1024.
-func TestBackhaulPoolDefaults(t *testing.T) {
- if defaultBackhaulMaxInflight != 256 {
- t.Fatalf("defaultBackhaulMaxInflight = %d, want 256", defaultBackhaulMaxInflight)
+ e := &Edge{}
+ if p := e.requestPool(); p.limit != backhaulMaxInflight.Load() || p.share != backhaulShare(backhaulClientShare, p.limit) {
+ t.Fatalf("request pool %d/%d", p.limit, p.share)
}
- if defaultBackhaulMaxStreams != 1024 {
- t.Fatalf("defaultBackhaulMaxStreams = %d, want 1024", defaultBackhaulMaxStreams)
- }
- if backhaulStreamClientShare != 64 {
- t.Fatalf("backhaulStreamClientShare = %d, want 64", backhaulStreamClientShare)
+ if p := e.streamPool(); p.limit != backhaulMaxStreams.Load() || p.share != backhaulShare(backhaulStreamClientShare, p.limit) {
+ t.Fatalf("stream pool %d/%d", p.limit, p.share)
}
}
@@ -164,8 +154,15 @@ func TestBackhaulPoolsAreSeparate(t *testing.T) {
func TestBackhaulStreamShare(t *testing.T) {
e, _, _ := hopEdge(t, "annie", "local.test")
e.rateMode = RateEnforce
- backhaulStreamCap(t, 128)
+ backhaulStreamCap(t, 256)
const a, b = "203.0.113.1/32", "203.0.113.2/32"
+ for i := 0; i < 64; i++ { // unkeyed: a quarter of the pool
+ rel, ok, _ := e.backhaulAcquireStream("betty", "")
+ if !ok {
+ t.Fatalf("unkeyed stream %d refused", i+1)
+ }
+ t.Cleanup(rel)
+ }
for i := 0; i < backhaulStreamClientShare; i++ {
rel, ok, shed := e.backhaulAcquireStream("betty", a)
if !ok || shed {
@@ -176,8 +173,8 @@ func TestBackhaulStreamShare(t *testing.T) {
if _, ok, shed := e.backhaulAcquireStream("betty", a); ok || !shed {
t.Fatalf("A over its share of a half-full stream pool: ok=%v shed=%v, want a fair-share refusal", ok, shed)
}
- if got := poolCount(&e.backhaulStreamInflight, "betty"); got != int64(backhaulStreamClientShare) {
- t.Fatalf("stream pool = %d after the refusal, want %d: the refusal must roll back", got, backhaulStreamClientShare)
+ if got := poolCount(&e.backhaulStreamInflight, "betty"); got != 64+int64(backhaulStreamClientShare) {
+ t.Fatalf("stream pool = %d after the refusal, want %d: the refusal must roll back", got, 64+backhaulStreamClientShare)
}
rel, ok, shed := e.backhaulAcquireStream("betty", b)
if !ok || shed {
@@ -191,6 +188,70 @@ func TestBackhaulStreamShare(t *testing.T) {
rel()
}
+// In a busy stream pool a client may hold exactly backhaulStreamClientShare
+// sockets, not the request pool's 8: a browser with several tabs open is
+// one visitor, not a flood.
+func TestBackhaulStreamShareInABusyPool(t *testing.T) {
+ e, _, _ := hopEdge(t, "annie", "local.test")
+ e.rateMode = RateEnforce
+ backhaulStreamCap(t, 256)
+ for i := 0; i < 128; i++ { // half full before A arrives
+ rel, ok, _ := e.backhaulAcquireStream("betty", "")
+ if !ok {
+ t.Fatalf("unkeyed stream %d refused", i+1)
+ }
+ t.Cleanup(rel)
+ }
+ const a = "203.0.113.1/32"
+ for i := 0; i < backhaulStreamClientShare; i++ {
+ rel, ok, shed := e.backhaulAcquireStream("betty", a)
+ if !ok || shed {
+ t.Fatalf("A's socket %d in a busy pool: ok=%v shed=%v, want admitted up to %d", i+1, ok, shed, backhaulStreamClientShare)
+ }
+ t.Cleanup(rel)
+ }
+ if _, ok, shed := e.backhaulAcquireStream("betty", a); ok || !shed {
+ t.Fatalf("A's socket %d: ok=%v shed=%v, want the fair-share refusal", backhaulStreamClientShare+1, ok, shed)
+ }
+}
+
+// A lowered cap scales the share down with it: at a cap of 8 one client may
+// hold 2 once the pool is half used, in either pool, not 8 or 64.
+func TestBackhaulShareScalesWithASmallCap(t *testing.T) {
+ for name, acquire := range map[string]func(*Edge) func(string, string) (func(), bool, bool){
+ "request": func(e *Edge) func(string, string) (func(), bool, bool) { return e.backhaulAcquire },
+ "stream": func(e *Edge) func(string, string) (func(), bool, bool) { return e.backhaulAcquireStream },
+ } {
+ e, _, _ := hopEdge(t, "annie", "local.test")
+ e.rateMode = RateEnforce
+ backhaulCap(t, 8)
+ backhaulStreamCap(t, 8)
+ take := acquire(e)
+ for i := 0; i < 4; i++ {
+ rel, ok, _ := take("betty", "")
+ if !ok {
+ t.Fatalf("%s: unkeyed slot %d refused", name, i+1)
+ }
+ t.Cleanup(rel)
+ }
+ for i := 0; i < 2; i++ {
+ rel, ok, shed := take("betty", "203.0.113.1/32")
+ if !ok || shed {
+ t.Fatalf("%s: A's slot %d: ok=%v shed=%v", name, i+1, ok, shed)
+ }
+ t.Cleanup(rel)
+ }
+ if _, ok, shed := take("betty", "203.0.113.1/32"); ok || !shed {
+ t.Fatalf("%s: A's third slot at a cap of 8: ok=%v shed=%v, want the share (2) refused", name, ok, shed)
+ }
+ if rel, ok, shed := take("betty", "203.0.113.2/32"); !ok || shed {
+ t.Fatalf("%s: B: ok=%v shed=%v, want a slot", name, ok, shed)
+ } else {
+ rel()
+ }
+ }
+}
+
// Under half full, the stream share takes no part.
func TestBackhaulStreamShareQuiet(t *testing.T) {
e, _, _ := hopEdge(t, "annie", "local.test")
@@ -213,9 +274,9 @@ func TestBackhaulStreamShareModes(t *testing.T) {
backhaulStreamCap(t, 128)
buf := captureLog(t)
for i := 0; i < backhaulStreamClientShare+1; i++ {
- rel, ok, shed := e.backhaulAcquireStream("betty", "203.0.113.1/32")
- if !ok || shed {
- t.Fatalf("mode %v stream %d: ok=%v shed=%v, want admitted", mode, i+1, ok, shed)
+ rel, err := e.backhaulStreamAt101("betty", "192.0.2.5", "203.0.113.1/32")
+ if err != nil {
+ t.Fatalf("mode %v stream %d: %v, want admitted", mode, i+1, err)
}
t.Cleanup(rel)
}
@@ -262,118 +323,184 @@ func TestBackhaulPoolsReleaseOnce(t *testing.T) {
}
}
-// Concurrent streams never exceed the stream cap and drift nothing; run
-// under -race.
-func TestBackhaulStreamsConcurrent(t *testing.T) {
+// Contention on both pools, round by round: more contenders than slots start
+// together, and at the barrier after every attempt the admitted holders are
+// within the cap, every attempt was either admitted or refused and counted,
+// each client's share count is its holders, and after the releases both
+// pools and every share are back at zero. Run under -race.
+func TestBackhaulPoolsUnderContention(t *testing.T) {
e, _, _ := hopEdge(t, "annie", "local.test")
e.rateMode = RateEnforce
- backhaulStreamCap(t, 16)
- var wg sync.WaitGroup
- for c := 0; c < 8; c++ {
- key := fmt.Sprintf("203.0.113.%d/32", c+1)
- wg.Add(1)
- go func() {
- defer wg.Done()
- for i := 0; i < 500; i++ {
- if rel, ok, _ := e.backhaulAcquireStream("betty", key); ok {
- if poolCount(&e.backhaulStreamInflight, "betty") > backhaulMaxStreams.Load() {
- t.Error("stream pool over its cap")
- }
- rel()
+ const slots, clients, perClient, rounds = 8, 4, 6, 25
+ backhaulCap(t, slots)
+ backhaulStreamCap(t, slots)
+ peers := []string{"203.0.113.1", "203.0.113.2", "203.0.113.3", "203.0.113.4"}
+
+ type attempt struct {
+ release func()
+ ok bool
+ }
+ pools := []struct {
+ name string
+ counts *sync.Map
+ shares *sync.Map
+ try func(peer string) (func(), bool)
+ }{
+ {"request", &e.backhaulInflight, &e.backhaulShares, func(peer string) (func(), bool) {
+ r := httptest.NewRequest(http.MethodGet, "http://example.com/", nil)
+ r.RemoteAddr = net.JoinHostPort(peer, "40000")
+ return e.backhaulAdmit(httptest.NewRecorder(), r, "192.0.2.5", "betty")
+ }},
+ {"stream", &e.backhaulStreamInflight, &e.backhaulStreamShares, func(peer string) (func(), bool) {
+ rel, err := e.backhaulStreamAt101("betty", "192.0.2.5", peer+"/32")
+ return rel, err == nil
+ }},
+ }
+ for _, p := range pools {
+ before := e.BackhaulSheds()
+ var refused int
+ for round := 0; round < rounds; round++ {
+ start := make(chan struct{})
+ results := make([]attempt, clients*perClient)
+ var wg sync.WaitGroup
+ for i := range results {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ rel, ok := p.try(peers[i%clients])
+ results[i] = attempt{rel, ok}
+ }()
+ }
+ close(start)
+ wg.Wait() // the barrier: every attempt has been admitted or refused
+ admitted := 0
+ perPeer := map[string]int{}
+ for i, a := range results {
+ if a.ok {
+ admitted++
+ perPeer[peers[i%clients]]++
+ } else {
+ refused++
}
}
- }()
- }
- wg.Wait()
- if got := poolCount(&e.backhaulStreamInflight, "betty"); got != 0 {
- t.Fatalf("stream pool = %d at rest, want 0", got)
+ if admitted > slots {
+ t.Fatalf("%s round %d: %d holders admitted over a cap of %d", p.name, round, admitted, slots)
+ }
+ if got := poolCount(p.counts, "betty"); got != int64(admitted) {
+ t.Fatalf("%s round %d: pool count %d, %d holders", p.name, round, got, admitted)
+ }
+ sv, _ := p.shares.Load("betty")
+ for _, peer := range peers {
+ if got := sv.(interface{ Held(string) int }).Held(peer + "/32"); got != perPeer[peer] {
+ t.Fatalf("%s round %d: %s's share count %d, %d holders", p.name, round, peer, got, perPeer[peer])
+ }
+ }
+ for _, a := range results {
+ if a.ok {
+ a.release()
+ a.release()
+ }
+ }
+ if got := poolCount(p.counts, "betty"); got != 0 {
+ t.Fatalf("%s round %d: pool count %d after every release", p.name, round, got)
+ }
+ for _, peer := range peers {
+ if got := sv.(interface{ Held(string) int }).Held(peer + "/32"); got != 0 {
+ t.Fatalf("%s round %d: %s still holds %d share(s)", p.name, round, peer, got)
+ }
+ }
+ }
+ after := e.BackhaulSheds()
+ counted := after.Requests + after.Streams + after.FairShare - before.Requests - before.Streams - before.FairShare
+ if counted != uint64(refused) {
+ t.Fatalf("%s: %d refusals, %d counted", p.name, refused, counted)
+ }
+ if refused < rounds*(clients*perClient-slots) {
+ t.Fatalf("%s: %d refusals over %d rounds of %d attempts at %d slots", p.name, refused, rounds, clients*perClient, slots)
+ }
}
}
-// backhaulAdmit chooses the pool from the request and counts each refusal it
-// answers: request-pool saturation and stream-pool saturation are both 503 +
-// Retry-After 2, a fair-share refusal is 429.
-func TestBackhaulAdmitPoolsAndShedCounts(t *testing.T) {
+// Each refusal is counted once by kind: the request pool's cap and share at
+// admission, the stream pool's cap and share at the 101.
+func TestBackhaulShedCounts(t *testing.T) {
e, _, _ := hopEdge(t, "annie", "local.test")
e.rateMode = RateEnforce
- backhaulCap(t, 1)
- backhaulStreamCap(t, 128)
+ backhaulCap(t, 4)
+ backhaulStreamCap(t, 4)
buf := captureLog(t)
-
- plain := func(peer string) *http.Request {
+ req := func(peer string) *http.Request {
r := httptest.NewRequest(http.MethodGet, "http://example.com/", nil)
r.RemoteAddr = net.JoinHostPort(peer, "40000")
return r
}
- socket := func(peer string) *http.Request {
- r := plain(peer)
- r.Header.Set("Connection", "Upgrade")
- r.Header.Set("Upgrade", "websocket")
- return r
- }
-
- // The request pool's only slot is held.
- held, ok := e.backhaulAdmit(httptest.NewRecorder(), plain(shareClientB), "192.0.2.5", "betty")
- if !ok {
- t.Fatal("the first request slot was refused")
+ // At a cap of 4 the share is 1, from 2 held: A gets 2 while the pool is
+ // quiet, then its third is refused.
+ for i := 0; i < 2; i++ {
+ rel, ok := e.backhaulAdmit(httptest.NewRecorder(), req(shareClientA), "192.0.2.5", "betty")
+ if !ok {
+ t.Fatalf("A's request %d refused", i+1)
+ }
+ t.Cleanup(rel)
}
- t.Cleanup(held)
rec := httptest.NewRecorder()
- if _, ok := e.backhaulAdmit(rec, plain(shareClientB), "192.0.2.5", "betty"); ok || rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") != "2" {
- t.Fatalf("request over the request cap: ok=%v %d Retry-After %q, want 503 + 2", ok, rec.Code, rec.Header().Get("Retry-After"))
+ if _, ok := e.backhaulAdmit(rec, req(shareClientA), "192.0.2.5", "betty"); ok || rec.Code != http.StatusTooManyRequests {
+ t.Fatalf("A over its request share: ok=%v %d, want 429", ok, rec.Code)
}
-
- // A's sockets still get streams with the request pool full.
- for i := 0; i < backhaulStreamClientShare; i++ {
- rel, ok := e.backhaulAdmit(httptest.NewRecorder(), socket(shareClientA), "192.0.2.5", "betty")
+ for i := 0; i < 2; i++ {
+ rel, ok, _ := e.backhaulAcquire("betty", "")
if !ok {
- t.Fatalf("A's socket %d refused with the request pool full", i+1)
+ t.Fatalf("unkeyed request %d refused below the cap", i+1)
}
t.Cleanup(rel)
}
rec = httptest.NewRecorder()
- if _, ok := e.backhaulAdmit(rec, socket(shareClientA), "192.0.2.5", "betty"); ok || rec.Code != http.StatusTooManyRequests {
- t.Fatalf("A's socket over its share: ok=%v %d, want 429", ok, rec.Code)
- }
- // A door caller from A's address is the box's own traffic: no share.
- door := socket(shareClientA)
- door = door.WithContext(context.WithValue(door.Context(), doorCallerKey{}, doorCaller{Account: "shop", App: "web"}))
- if rel, ok := e.backhaulAdmit(httptest.NewRecorder(), door, "192.0.2.5", "betty"); !ok {
- t.Fatal("a door caller's socket was shed")
- } else {
+ if _, ok := e.backhaulAdmit(rec, req(shareClientB), "192.0.2.5", "betty"); ok || rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") != "2" {
+ t.Fatalf("over the request cap: ok=%v %d Retry-After %q, want 503 + 2", ok, rec.Code, rec.Header().Get("Retry-After"))
+ }
+ for i := 0; i < 2; i++ {
+ rel, err := e.backhaulStreamAt101("betty", "192.0.2.5", shareClientA+"/32")
+ if err != nil {
+ t.Fatalf("A's stream %d: %v", i+1, err)
+ }
t.Cleanup(rel)
}
-
- // Fill the stream pool with B's sockets (B is under its share).
- backhaulStreamCap(t, poolCount(&e.backhaulStreamInflight, "betty")+1)
- rel, ok := e.backhaulAdmit(httptest.NewRecorder(), socket(shareClientB), "192.0.2.5", "betty")
- if !ok {
- t.Fatal("B's socket refused below the stream cap")
+ if _, err := e.backhaulStreamAt101("betty", "192.0.2.5", shareClientA+"/32"); !errors.Is(err, errBackhaulStreamShare) {
+ t.Fatalf("A over its stream share: %v", err)
}
- t.Cleanup(rel)
- rec = httptest.NewRecorder()
- if _, ok := e.backhaulAdmit(rec, socket(shareClientB), "192.0.2.5", "betty"); ok || rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") != "2" {
- t.Fatalf("socket over the stream cap: ok=%v %d Retry-After %q, want 503 + 2", ok, rec.Code, rec.Header().Get("Retry-After"))
+ for i := 0; i < 2; i++ {
+ rel, err := e.backhaulStreamAt101("betty", "192.0.2.5", "")
+ if err != nil {
+ t.Fatalf("unkeyed stream %d: %v", i+1, err)
+ }
+ t.Cleanup(rel)
}
-
- if got, want := e.BackhaulSheds(), (BackhaulSheds{Requests: 1, Streams: 1, FairShare: 1}); got != want {
+ if _, err := e.backhaulStreamAt101("betty", "192.0.2.5", ""); !errors.Is(err, errBackhaulStreamsBusy) {
+ t.Fatalf("over the stream cap: %v", err)
+ }
+ if got, want := e.BackhaulSheds(), (BackhaulSheds{Requests: 1, Streams: 1, FairShare: 2}); got != want {
t.Fatalf("BackhaulSheds = %+v, want %+v", got, want)
}
out := buf.String()
- if !strings.Contains(out, "in-flight cap") || !strings.Contains(out, "stream cap") {
+ if !strings.Contains(out, "in-flight cap (4); answering 503 with Retry-After: 2") ||
+ !strings.Contains(out, "stream cap (4 open WebSockets); answering 503 with Retry-After: 2") {
t.Fatalf("log lacks a line for each saturated pool: %s", out)
}
- // Two throttle keys, so each saturation is its own first occurrence;
- // the share refusal is a third.
- if n := strings.Count(out, "occurrence #1"); n != 3 {
- t.Fatalf("%d first-occurrence lines, want 3 (request cap, stream share, stream cap): %s", n, out)
+ if strings.ContainsAny(out, "—–") {
+ t.Fatalf("a backhaul log line has a dash: %s", out)
+ }
+ // Four throttle keys: each pool's cap and each pool's share.
+ if n := strings.Count(out, "occurrence #1"); n != 4 {
+ t.Fatalf("%d first-occurrence lines, want 4: %s", n, out)
}
}
// wsHome is a home edge that answers an upgrade with 101 and holds the
// socket open, echoing each line, until the test ends; any other request
-// gets the ordinary body. reject makes it answer upgrades 400 instead.
-func wsHome(t *testing.T, reject bool) http.Handler {
+// gets the ordinary body. With slow set it answers an upgrade request 200
+// instead, with a body it finishes only when slow is closed.
+func wsHome(t *testing.T, slow chan struct{}) http.Handler {
t.Helper()
stop := make(chan struct{})
t.Cleanup(func() { close(stop) })
@@ -382,8 +509,11 @@ func wsHome(t *testing.T, reject bool) http.Handler {
fmt.Fprint(w, homeEdgeBody)
return
}
- if reject {
- http.Error(w, "no sockets here", http.StatusBadRequest)
+ if slow != nil {
+ fmt.Fprint(w, "first ")
+ w.(http.Flusher).Flush()
+ <-slow
+ fmt.Fprint(w, "last")
return
}
conn, buf, err := w.(http.Hijacker).Hijack()
@@ -409,9 +539,10 @@ func wsHome(t *testing.T, reject bool) http.Handler {
})
}
-// openBackhaulSocket opens one WebSocket-shaped upgrade through the sending edge at
-// srv and returns the connection, or the refusal's response.
-func openBackhaulSocket(t *testing.T, srv *httptest.Server) (net.Conn, *http.Response) {
+// openBackhaulSocket opens one WebSocket-shaped upgrade through the sending
+// edge at srv, from peer when it is not empty (rlPeerHeader), and returns
+// the connection, or the refusal's response.
+func openBackhaulSocket(t *testing.T, srv *httptest.Server, peer string) (net.Conn, *http.Response) {
t.Helper()
c, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://"))
if err != nil {
@@ -421,7 +552,11 @@ func openBackhaulSocket(t *testing.T, srv *httptest.Server) (net.Conn, *http.Res
if err := c.SetDeadline(time.Now().Add(15 * time.Second)); err != nil {
t.Fatal(err)
}
- if _, err := fmt.Fprint(c, "GET /cable HTTP/1.1\r\nHost: example.com\r\nConnection: keep-alive, Upgrade\r\nUpgrade: websocket\r\n\r\n"); err != nil {
+ hdr := ""
+ if peer != "" {
+ hdr = rlPeerHeader + ": " + peer + "\r\n"
+ }
+ if _, err := fmt.Fprintf(c, "GET /cable HTTP/1.1\r\nHost: example.com\r\nConnection: keep-alive, Upgrade\r\nUpgrade: websocket\r\n%s\r\n", hdr); err != nil {
t.Fatalf("write handshake: %v", err)
}
br := bufio.NewReader(c)
@@ -441,16 +576,32 @@ func openBackhaulSocket(t *testing.T, srv *httptest.Server) (net.Conn, *http.Res
return c, resp
}
+// peerFront serves e behind a front that takes each request's peer address
+// from rlPeerHeader, as shareScene does.
+func peerFront(t *testing.T, e *Edge) *httptest.Server {
+ t.Helper()
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if p := r.Header.Get(rlPeerHeader); p != "" {
+ r.Header.Del(rlPeerHeader)
+ r.RemoteAddr = net.JoinHostPort(p, "40000")
+ }
+ e.ServeHTTP(w, r)
+ }))
+ t.Cleanup(srv.Close)
+ return srv
+}
+
// The incident, end to end through the real backhaul handler: more open
-// WebSockets than the request pool has slots, and ordinary GETs to the same
-// home box still succeed. Then the stream pool itself saturates with 503 +
-// Retry-After 2, and a socket that ends gives its slot back.
+// WebSockets than the request pool has slots, each moved to the stream pool
+// at its 101, and ordinary GETs to the same home box still succeed. Then the
+// stream pool saturates: the next 101 is refused with 503 + Retry-After 2,
+// no slot leaks in either pool, and a socket that ends gives its slot back.
func TestBackhaulWebSocketsDoNotStarveRequests(t *testing.T) {
e, m, _ := hopEdge(t, "annie", "local.test")
const n = 3
backhaulCap(t, n)
backhaulStreamCap(t, n+2)
- _, eip := fakeHomeEdge(t, wsHome(t, false))
+ rec, eip := fakeHomeEdge(t, wsHome(t, nil))
homedOn(t, m, "betty", eip, "example.com")
srv := httptest.NewServer(e)
t.Cleanup(srv.Close)
@@ -458,7 +609,7 @@ func TestBackhaulWebSocketsDoNotStarveRequests(t *testing.T) {
var socks []net.Conn
for i := 0; i < n+1; i++ {
- c, resp := openBackhaulSocket(t, srv)
+ c, resp := openBackhaulSocket(t, srv, "")
if c == nil {
t.Fatalf("socket %d refused: %d", i+1, resp.StatusCode)
}
@@ -468,7 +619,7 @@ func TestBackhaulWebSocketsDoNotStarveRequests(t *testing.T) {
t.Fatalf("stream pool = %d with %d sockets open, want %d", got, n+1, n+1)
}
if got := poolCount(&e.backhaulInflight, "betty"); got != 0 {
- t.Fatalf("request pool = %d with only sockets open, want 0", got)
+ t.Fatalf("request pool = %d with only sockets open, want 0: each gave its request slot back at its 101", got)
}
for i := 0; i < 2*n; i++ {
resp, err := get("example.com")
@@ -482,98 +633,138 @@ func TestBackhaulWebSocketsDoNotStarveRequests(t *testing.T) {
}
}
- c, _ := openBackhaulSocket(t, srv) // the pool's last slot
+ c, _ := openBackhaulSocket(t, srv, "") // the pool's last slot
if c == nil {
t.Fatal("socket n+2 refused below the stream cap")
}
socks = append(socks, c)
- _, refused := openBackhaulSocket(t, srv)
- if refused == nil || refused.StatusCode != http.StatusServiceUnavailable || refused.Header.Get("Retry-After") != "2" {
- t.Fatalf("socket over the stream cap: %+v, want 503 + Retry-After 2", refused)
+ homeSaw := rec.get().n
+ _, refused := openBackhaulSocket(t, srv, "")
+ if refused == nil || refused.StatusCode != http.StatusServiceUnavailable || refused.Header.Get("Retry-After") != "2" ||
+ refused.Header.Get("X-Carlos-Answer") != "backhaul-streams-busy" {
+ t.Fatalf("socket over the stream cap: %+v, want 503 + Retry-After 2 from backhaul-streams-busy", refused)
+ }
+ io.Copy(io.Discard, refused.Body)
+ if rec.get().n != homeSaw+1 {
+ t.Fatal("the refused socket never reached the home: it must be refused at the 101, not at admission")
}
if got := e.BackhaulSheds(); got.Streams != 1 || got.Requests != 0 {
t.Fatalf("BackhaulSheds = %+v, want one stream shed", got)
}
+ waitFor(t, 10*time.Second, "the refused hop's request slot back", func() bool {
+ return poolCount(&e.backhaulInflight, "betty") == 0
+ })
+ if got := poolCount(&e.backhaulStreamInflight, "betty"); got != n+2 {
+ t.Fatalf("stream pool = %d after the refusal, want %d", got, n+2)
+ }
socks[0].Close()
waitFor(t, 10*time.Second, "a closed socket's slot back", func() bool {
return poolCount(&e.backhaulStreamInflight, "betty") == n+1
})
- if c, resp := openBackhaulSocket(t, srv); c == nil {
+ if c, resp := openBackhaulSocket(t, srv, ""); c == nil {
t.Fatalf("socket after one closed: %d, want 101", resp.StatusCode)
}
}
-// With the request pool full, a socket still opens, and a GET is still 503.
-func TestBackhaulRequestSaturationLeavesStreams(t *testing.T) {
+// The Upgrade header buys nothing: an upgrade request the home answers 200
+// with a long body holds a request slot for its whole life and never a
+// stream slot, and with the request pool full an upgrade request is refused
+// like any other.
+func TestBackhaulUpgradeRequestAnswered200StaysInRequestPool(t *testing.T) {
e, m, _ := hopEdge(t, "annie", "local.test")
- backhaulCap(t, 1)
- _, eip := fakeHomeEdge(t, wsHome(t, false))
+ slow := make(chan struct{})
+ _, eip := fakeHomeEdge(t, wsHome(t, slow))
homedOn(t, m, "betty", eip, "example.com")
- rel, ok, _ := e.backhaulAcquire("betty", "")
- if !ok {
- t.Fatal("first request slot refused")
- }
- t.Cleanup(rel)
srv := httptest.NewServer(e)
t.Cleanup(srv.Close)
- resp, err := backhaulGetter(t, e)("example.com")
- if err != nil {
- t.Fatal(err)
+ c, resp := openBackhaulSocket(t, srv, "")
+ if c != nil || resp.StatusCode != http.StatusOK {
+ t.Fatalf("upgrade request answered 200: %+v", resp)
+ }
+ first := make([]byte, len("first "))
+ if _, err := io.ReadFull(resp.Body, first); err != nil || string(first) != "first " {
+ t.Fatalf("first chunk %q (%v)", first, err)
+ }
+ if got := poolCount(&e.backhaulInflight, "betty"); got != 1 {
+ t.Fatalf("request pool = %d mid-body, want 1", got)
+ }
+ if got := poolCount(&e.backhaulStreamInflight, "betty"); got != 0 {
+ t.Fatalf("stream pool = %d, want 0: no 101, no stream slot", got)
}
- resp.Body.Close()
- if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "2" {
- t.Fatalf("GET with the request pool full: %d Retry-After %q, want 503 + 2", resp.StatusCode, resp.Header.Get("Retry-After"))
+ close(slow)
+ if rest, err := io.ReadAll(resp.Body); err != nil || string(rest) != "last" {
+ t.Fatalf("rest %q (%v)", rest, err)
}
- if c, resp := openBackhaulSocket(t, srv); c == nil {
- t.Fatalf("socket with the request pool full: %d, want 101", resp.StatusCode)
+ waitFor(t, 10*time.Second, "the request slot back", func() bool {
+ return poolCount(&e.backhaulInflight, "betty") == 0
+ })
+
+ backhaulCap(t, 1)
+ rel, ok, _ := e.backhaulAcquire("betty", "")
+ if !ok {
+ t.Fatal("request slot refused")
+ }
+ t.Cleanup(rel)
+ if c, resp := openBackhaulSocket(t, srv, ""); c != nil || resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "2" {
+ t.Fatalf("upgrade request with the request pool full: %+v, want 503 + Retry-After 2", resp)
}
}
-// An upgrade request the home answers without switching protocols still
-// gives its stream slot back when the hop ends.
-func TestBackhaulRefusedUpgradeReleasesStreamSlot(t *testing.T) {
+// The stream share through the real handler with real client addresses: a
+// client over its share of a busy stream pool gets the 429 at its 101,
+// another client still gets sockets, and the refused hop leaks no slot.
+func TestBackhaulStreamShareAt101(t *testing.T) {
e, m, _ := hopEdge(t, "annie", "local.test")
- _, eip := fakeHomeEdge(t, wsHome(t, true))
+ e.rateMode = RateEnforce
+ backhaulStreamCap(t, 8) // share 2, busy from 4 held
+ _, eip := fakeHomeEdge(t, wsHome(t, nil))
homedOn(t, m, "betty", eip, "example.com")
- srv := httptest.NewServer(e)
- t.Cleanup(srv.Close)
- c, resp := openBackhaulSocket(t, srv)
- if c != nil || resp.StatusCode != http.StatusBadRequest {
- t.Fatalf("upgrade the home refused: %+v, want its 400", resp)
+ srv := peerFront(t, e)
+
+ for i := 0; i < 4; i++ {
+ if c, resp := openBackhaulSocket(t, srv, shareClientB); c == nil {
+ t.Fatalf("B's socket %d: %d", i+1, resp.StatusCode)
+ }
+ }
+ for i := 0; i < 2; i++ {
+ if c, resp := openBackhaulSocket(t, srv, shareClientA); c == nil {
+ t.Fatalf("A's socket %d: %d", i+1, resp.StatusCode)
+ }
}
- waitFor(t, 10*time.Second, "the stream slot back", func() bool {
- return poolCount(&e.backhaulStreamInflight, "betty") == 0
+ _, resp := openBackhaulSocket(t, srv, shareClientA)
+ if resp.StatusCode != http.StatusTooManyRequests {
+ t.Fatalf("A's third socket in a busy pool of 8: %d, want 429", resp.StatusCode)
+ }
+ if got := e.BackhaulSheds(); got != (BackhaulSheds{FairShare: 1}) {
+ t.Fatalf("BackhaulSheds = %+v, want one share refusal", got)
+ }
+ waitFor(t, 10*time.Second, "the refused hop's request slot back", func() bool {
+ return poolCount(&e.backhaulInflight, "betty") == 0
})
- if got := poolCount(&e.backhaulInflight, "betty"); got != 0 {
- t.Fatalf("request pool = %d, want 0: the upgrade never took a request slot", got)
+ if got := poolCount(&e.backhaulStreamInflight, "betty"); got != 6 {
+ t.Fatalf("stream pool = %d, want the 6 open sockets", got)
+ }
+ if c, resp := openBackhaulSocket(t, srv, "203.0.113.9"); c == nil {
+ t.Fatalf("another client's socket: %d, want 101", resp.StatusCode)
}
}
-// In a busy stream pool a client may hold exactly backhaulStreamClientShare
-// sockets, not the request pool's 8: a browser with several tabs open is
-// one visitor, not a flood.
-func TestBackhaulStreamShareInABusyPool(t *testing.T) {
+// A door caller is the box's own traffic: no share at the 101 either.
+func TestBackhaulStreamDoorExempt(t *testing.T) {
e, _, _ := hopEdge(t, "annie", "local.test")
e.rateMode = RateEnforce
- backhaulStreamCap(t, 256)
- for i := 0; i < 128; i++ { // half full before A arrives
- rel, ok, _ := e.backhaulAcquireStream("betty", "")
- if !ok {
- t.Fatalf("unkeyed stream %d refused", i+1)
- }
- t.Cleanup(rel)
- }
- const a = "203.0.113.1/32"
- for i := 0; i < backhaulStreamClientShare; i++ {
- rel, ok, shed := e.backhaulAcquireStream("betty", a)
- if !ok || shed {
- t.Fatalf("A's socket %d in a busy pool: ok=%v shed=%v, want admitted up to %d", i+1, ok, shed, backhaulStreamClientShare)
+ backhaulStreamCap(t, 8)
+ r := httptest.NewRequest(http.MethodGet, "http://example.com/", nil)
+ r.RemoteAddr = net.JoinHostPort(shareClientA, "40000")
+ r = r.WithContext(context.WithValue(r.Context(), doorCallerKey{}, doorCaller{Account: "shop", App: "web"}))
+ key := e.backhaulClientKey(r)
+ for i := 0; i < 8; i++ {
+ rel, err := e.backhaulStreamAt101("betty", "192.0.2.5", key)
+ if err != nil {
+ t.Fatalf("door caller's socket %d: %v", i+1, err)
}
t.Cleanup(rel)
}
- if _, ok, shed := e.backhaulAcquireStream("betty", a); ok || !shed {
- t.Fatalf("A's socket %d: ok=%v shed=%v, want the fair-share refusal", backhaulStreamClientShare+1, ok, shed)
- }
}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index f6fe1ad4c..75702ba21 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -68,7 +68,6 @@ import (
"github.com/carlosframework/platform/internal/reqrec"
"github.com/carlosframework/platform/internal/tunnelclient"
"golang.org/x/crypto/acme/autocert"
- "golang.org/x/net/http/httpguts"
)
// Default cache sizing for EnableCache: 4096 entries is comfortably above a
@@ -4692,12 +4691,13 @@ func fleetProxy(fleet, boxLabel string, authoritative bool, hub *TunnelHub) *htt
// box at a time, counted on the SENDING edge. At the limit the sender answers
// 503 + Retry-After: 2 (backhaulAdmit, below) rather than dialling.
//
-// Since #1535 it is one of TWO pools per destination box. An upgrade request
-// (a WebSocket) holds its slot for the life of the socket, so a few dozen
+// Since #1535 it is one of TWO pools per destination box. An upgraded hop (a
+// WebSocket) holds its slot for the life of the socket, so a few dozen
// dashboard tabs holding sockets open filled the old single cap of 64 and
-// every ordinary request to that box got 503. Upgrades now take their slot
-// from the stream pool (backhaulMaxStreams), so this pool only ever holds
-// hops that end when their response does, and its default is 256.
+// every ordinary request to that box got 503. Every hop is still admitted
+// here, upgrade request or not, and one the home answers with a 101 moves to
+// the stream pool (backhaulMaxStreams) at that moment (hopTo). So this pool
+// holds no open sockets, and its default is 128.
//
// A concurrency bound and not a rate: cross-region egress is (concurrent
// streams × per-stream bandwidth), so a request-rate cap would neither bound
@@ -4723,26 +4723,39 @@ func fleetProxy(fleet, boxLabel string, authoritative bool, hub *TunnelHub) *htt
// would turn a plain int into a real data race rather than a stale read.
var backhaulMaxInflight atomic.Int64
-const defaultBackhaulMaxInflight = 256
+const defaultBackhaulMaxInflight = 128
// backhaulMaxStreams is the stream pool's cap: at most this many upgraded
// hops (WebSockets) may be open toward any one home box at a time, counted
// on the sending edge like backhaulMaxInflight and for the same egress
-// ruling. Saturation is the same 503 + Retry-After: 2. A var and atomic for
-// backhaulMaxInflight's reasons.
+// ruling. A var and atomic for backhaulMaxInflight's reasons.
//
-// The pool is chosen from the REQUEST at admission (backhaulUpgrade), before
-// the home has answered. An upgrade request whose response turns out not to
-// be 101 still holds its stream slot until the hop ends, which for such a
-// response is when its body has been sent: brief, and on the safe side.
+// The pool is chosen from the RESPONSE, as the home edge's own rate limit
+// does (ServeHTTP's upgrade branch): the Upgrade header is the client's to
+// send, so it must not buy a request out of the request pool. A hop is
+// admitted on a request slot, and only when the home answers 101 does it
+// take a stream slot (with the stream pool's own fair share, for the same
+// client key) and give the request slot back (backhaulStreamAt101). A
+// stream pool with no room fails the hop there: the backend connection is
+// closed and the client gets 503 + Retry-After: 2, or the 429 for a share
+// refusal. So a stream slot is only ever a real upgraded socket.
+//
+// What a socket costs, estimated and not measured: about 100 KB per upgraded
+// hop on each of the two boxes, from the proxy's two 32 KiB copy buffers,
+// the TLS state and three goroutines. A full default pool is about 50 MB on
+// the sender and the same on the home box per sending sibling. The home box
+// carries that same cost for a visitor who opens the socket to it directly,
+// and it has no cap on direct upgrades (planthrottle.go's refusal of a
+// throttled account aside), so a relayed socket adds no exposure beyond the
+// same visitors connecting directly. The sum over the home box's siblings is
+// the worst case.
//
// Not reclassified in this slice: a long-lived response to an ordinary
// request (server-sent events, a long poll) still holds a request-pool slot
-// for its life. Moving those to the stream pool needs the response, not the
-// request, and is a follow-up.
+// for its life. Moving those is a follow-up.
var backhaulMaxStreams atomic.Int64
-const defaultBackhaulMaxStreams = 1024
+const defaultBackhaulMaxStreams = 512
func init() {
backhaulMaxInflight.Store(defaultBackhaulMaxInflight)
@@ -4769,7 +4782,7 @@ func backhaulCapFromEnv(name string, def int, what string) int {
}
n, err := strconv.Atoi(raw)
if err != nil || n <= 0 {
- log.Printf("edge: %s=%q is not a positive integer — using the default of %d %s", name, raw, def, what)
+ log.Printf("edge: %s=%q is not a positive integer; using the default of %d %s", name, raw, def, what)
return def
}
return n
@@ -4777,31 +4790,27 @@ func backhaulCapFromEnv(name string, def int, what string) int {
// backhaulClientShare is the most slots one client may hold toward a
// destination box while the box is at least half full. A fixed number, not a
-// setting: the sending edge has no route row to read one from (#358).
+// setting: the sending edge has no route row to read one from (#358). It is
+// scaled down for a small cap (backhaulShare).
const backhaulClientShare = 8
// backhaulStreamClientShare is the same for the stream pool: the most open
// sockets one client may hold toward a box while that box's stream pool is
// at least half full. Larger than backhaulClientShare because a real
// visitor's browser holds several sockets for as long as its tabs are open,
-// and smaller than half the default pool, so one client cannot fill it.
+// and an eighth of the default pool, so one client cannot fill it.
const backhaulStreamClientShare = 64
+// backhaulShare is a pool's per-client share at cap limit: the pool's
+// constant, but never more than a quarter of the cap (and at least one), so
+// an operator who lowers a cap does not leave one client able to fill it.
+func backhaulShare(share int, limit int64) int {
+ return int(min(int64(share), max(1, limit/4)))
+}
+
// backhaulSharesMaxKeys bounds the clients tracked per destination box.
const backhaulSharesMaxKeys = 10_000
-// backhaulUpgrade reports whether r asks to switch protocols: its Connection
-// header carries the "upgrade" token and it has an Upgrade header. The same
-// test net/http's reverse proxy uses to take its upgrade path, so a request
-// that takes a stream slot is exactly one the hop may turn into a socket.
-// A client can claim this for any request by sending the headers; that
-// moves it to a pool that is just as capped and fair-shared, and so gains
-// it nothing the stream pool's own bounds do not already allow.
-func backhaulUpgrade(r *http.Request) bool {
- return httpguts.HeaderValuesContainsToken(r.Header["Connection"], "Upgrade") &&
- strings.TrimSpace(r.Header.Get("Upgrade")) != ""
-}
-
// backhaulClientKey is the fair-share key of the client behind r, or "" when
// r is not shared out: the limiter is off, a door caller (the box's own
// traffic), a request that came over a fleet tunnel (its address is the hub's,
@@ -4831,12 +4840,14 @@ type backhaulPool struct {
}
func (e *Edge) requestPool() backhaulPool {
- return backhaulPool{&e.backhaulInflight, &e.backhaulShares, backhaulMaxInflight.Load(), backhaulClientShare,
+ limit := backhaulMaxInflight.Load()
+ return backhaulPool{&e.backhaulInflight, &e.backhaulShares, limit, backhaulShare(backhaulClientShare, limit),
"backhaul-share ", "slots"}
}
func (e *Edge) streamPool() backhaulPool {
- return backhaulPool{&e.backhaulStreamInflight, &e.backhaulStreamShares, backhaulMaxStreams.Load(), backhaulStreamClientShare,
+ limit := backhaulMaxStreams.Load()
+ return backhaulPool{&e.backhaulStreamInflight, &e.backhaulStreamShares, limit, backhaulShare(backhaulStreamClientShare, limit),
"backhaul-streams-share ", "stream slots"}
}
@@ -4867,10 +4878,11 @@ func (e *Edge) backhaulAcquire(box, clientKey string) (releaseSlot func(), ok bo
return e.acquirePoolSlot(e.requestPool(), box, clientKey)
}
-// backhaulAcquireStream is backhaulAcquire over the stream pool, for an
-// upgrade request: its own counts, its own cap (backhaulMaxStreams) and its
-// own fair share (backhaulStreamClientShare), with every rule above. An
-// upgraded hop holds its slot for the life of the socket.
+// backhaulAcquireStream is backhaulAcquire over the stream pool, for a hop
+// the home has answered with a 101: its own counts, its own cap
+// (backhaulMaxStreams) and its own fair share (backhaulStreamClientShare),
+// with every rule above. An upgraded hop holds its slot for the life of the
+// socket.
func (e *Edge) backhaulAcquireStream(box, clientKey string) (releaseSlot func(), ok bool, shed bool) {
return e.acquirePoolSlot(e.streamPool(), box, clientKey)
}
@@ -4908,7 +4920,7 @@ func (e *Edge) acquirePoolSlot(p backhaulPool, box, clientKey string) (releaseSl
verb = "would refuse"
}
e.logThrottled(p.logKey+box, fmt.Sprintf(
- "backhaul to %s is at least half full (%d of %d %s) and client %s holds %d of them — %s the request (fair share %d)",
+ "backhaul to %s is at least half full (%d of %d %s) and client %s holds %d of them; %s the request (fair share %d)",
box, held-1, p.limit, p.slots, clientKey, shares.Held(clientKey), verb, p.share))
if e.rateMode == RateEnforce {
n.Add(-1)
@@ -4930,9 +4942,10 @@ func (e *Edge) acquirePoolSlot(p backhaulPool, box, clientKey string) (releaseSl
// BackhaulSheds is how many hops this edge's backhaul has refused since it
// started, by kind: request-pool saturation and stream-pool saturation (both
-// a 503) and fair-share refusals (a 429). Observe mode's "would refuse" is
-// not a refusal and is not counted. The agent's metrics loop reads it once a
-// tick for the backhaul_shed rule.
+// a 503) and fair-share refusals of either pool (a 429). Observe mode's
+// "would refuse" is not a refusal and is not counted. The agent's metrics
+// loop reads it once a tick: all three go into the metrics sample, and the
+// two saturation kinds feed the backhaul_shed rule.
type BackhaulSheds struct {
Requests uint64
Streams uint64
@@ -5026,14 +5039,20 @@ func (e *Edge) backhaulTo(w http.ResponseWriter, r *http.Request, host, eip, box
func (e *Edge) hopTo(w http.ResponseWriter, r *http.Request, host, eip, box string, key []byte, event string, tr http.RoundTripper,
onError func(http.ResponseWriter, *http.Request, error), onResponse func(*http.Response)) bool {
// Containment (the egress ruling, 2026-08-24), between the last guard and
- // the dial: backhaulAdmit answers a refused hop itself.
+ // the dial: backhaulAdmit answers a refused hop itself. Every hop starts
+ // on a request slot, upgrade request or not (backhaulMaxStreams).
+ clientKey := e.backhaulClientKey(r)
releaseSlot, ok := e.backhaulAdmit(w, r, eip, box)
if !ok {
return false
}
- // Held until the hop's ServeHTTP returns, which for a stream or an
- // upgraded connection is the life of the stream (backhaulAcquire).
- defer releaseSlot()
+ // Held until the hop's ServeHTTP returns, which for a stream is the
+ // life of the stream (backhaulAcquire). A 101 swaps it for a stream
+ // slot (below) before the proxy hijacks the connection. The swap runs
+ // in the proxy's ModifyResponse, on this goroutine, so slot needs no
+ // lock.
+ slot := releaseSlot
+ defer func() { slot() }()
// The MAC is over the CONCRETE request host — never the wildcard map key
// that may have matched it — because the home edge verifies against its own
// literal request host (hopMAC canonicalizes both, mesh.go).
@@ -5056,6 +5075,40 @@ func (e *Edge) hopTo(w http.ResponseWriter, r *http.Request, host, eip, box stri
return scrub(resp)
}
}
+ // A 101 is an open socket from here on: it takes a stream slot and gives
+ // the request slot back, or the hop fails. A refusal returned from
+ // ModifyResponse makes the proxy close the backend connection (the 101's
+ // body) and call ErrorHandler, which answers it below, before any other
+ // error handling (a retry must not take a refused upgrade elsewhere).
+ modify := p.ModifyResponse
+ p.ModifyResponse = func(resp *http.Response) error {
+ if resp.StatusCode == http.StatusSwitchingProtocols {
+ stream, err := e.backhaulStreamAt101(box, eip, clientKey)
+ if err != nil {
+ return err
+ }
+ request := slot
+ slot = stream
+ request()
+ }
+ if modify == nil {
+ return nil
+ }
+ return modify(resp)
+ }
+ fail := p.ErrorHandler
+ p.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
+ switch {
+ case errors.Is(err, errBackhaulStreamShare):
+ writeRateLimited(w, time.Second)
+ case errors.Is(err, errBackhaulStreamsBusy):
+ Unavailable(w, "backhaul-streams-busy", "temporarily busy", 2)
+ case fail != nil:
+ fail(w, r, err)
+ default:
+ w.WriteHeader(http.StatusBadGateway)
+ }
+ }
// The client boundary for informational responses: a 1xx from the home
// reaches w through the proxy's trace hook, past ModifyResponse, so the
// asset vocabulary comes off it here (assetInformationalScrub).
@@ -5064,36 +5117,25 @@ func (e *Edge) hopTo(w http.ResponseWriter, r *http.Request, host, eip, box stri
return true
}
-// backhaulAdmit takes one backhaul slot toward box for r's client, from the
-// stream pool for an upgrade request (backhaulUpgrade) and the request pool
-// for everything else, or answers the refusal on w and reports false. It is
-// the one place every refusal is written and counted (BackhaulSheds), for an
-// ordinary hop (backhaulTo) and, through backhaulAdmitPool, for a far asset
-// fill (serveAssetFar).
+// backhaulAdmit takes one request-pool slot toward box for r's client
+// (backhaulAcquire with backhaulClientKey), or answers the refusal on w and
+// reports false. It is the one place a hop's admission refusals are written
+// and counted (BackhaulSheds), for an ordinary hop (hopTo) and for a far
+// asset fill (serveAssetFar). An upgrade request is admitted here like any
+// other; its stream slot is taken at the 101 (backhaulStreamAt101).
//
// A saturated home box is answered here, with no dial and no bytes crossing
// a region. 503 + Retry-After: 2 is this package's established "come back
// shortly" (staleHopRefusal, fleetProxy) and is deliberately NOT the
// unknown-host answer — that is a 302 on a fallback edge, which would lie to
// a legitimate client about where its app lives. The log key is per home
-// BOX and per pool, like "backhaul-error "+box in backhaulProxy and for the
-// same bounded-key reason. A fair-share refusal is the 429 the home edge
-// gives.
+// BOX, like "backhaul-error "+box in backhaulProxy and for the same
+// bounded-key reason. A fair-share refusal is the 429 the home edge gives.
//
// The caller releases the slot exactly once, when its exchange with the home
// is over (backhaulAcquire).
func (e *Edge) backhaulAdmit(w http.ResponseWriter, r *http.Request, eip, box string) (releaseSlot func(), ok bool) {
- return e.backhaulAdmitPool(w, r, eip, box, backhaulUpgrade(r))
-}
-
-// backhaulAdmitPool is backhaulAdmit with the pool chosen by the caller:
-// stream true for the stream pool.
-func (e *Edge) backhaulAdmitPool(w http.ResponseWriter, r *http.Request, eip, box string, stream bool) (releaseSlot func(), ok bool) {
- acquire := e.backhaulAcquire
- if stream {
- acquire = e.backhaulAcquireStream
- }
- releaseSlot, ok, shed := acquire(box, e.backhaulClientKey(r))
+ releaseSlot, ok, shed := e.backhaulAcquire(box, e.backhaulClientKey(r))
if shed {
// The fair share, not saturation: this client holds its share of a
// busy hop. The same 429 the home edge gives (writeRateLimited).
@@ -5102,21 +5144,42 @@ func (e *Edge) backhaulAdmitPool(w http.ResponseWriter, r *http.Request, eip, bo
return nil, false
}
if !ok {
- if stream {
- e.backhaulShed.streams.Add(1)
- e.logThrottled("backhaul-streams-saturated "+box,
- fmt.Sprintf("backhaul to %s (%s) is at its stream cap (%d open WebSockets); answering 503 + Retry-After: 2", box, eip, backhaulMaxStreams.Load()))
- } else {
- e.backhaulShed.requests.Add(1)
- e.logThrottled("backhaul-saturated "+box,
- fmt.Sprintf("backhaul to %s (%s) is at its in-flight cap (%d) — answering 503 + Retry-After: 2", box, eip, backhaulMaxInflight.Load()))
- }
+ e.backhaulShed.requests.Add(1)
+ e.logThrottled("backhaul-saturated "+box,
+ fmt.Sprintf("backhaul to %s (%s) is at its in-flight cap (%d); answering 503 with Retry-After: 2", box, eip, backhaulMaxInflight.Load()))
Unavailable(w, "backhaul-busy", "temporarily busy", 2)
return nil, false
}
return releaseSlot, true
}
+// The refusals backhaulStreamAt101 returns, which hopTo's ErrorHandler
+// answers: the stream pool's fair share (429) and its cap (503).
+var (
+ errBackhaulStreamShare = errors.New("backhaul: client holds its share of the stream pool")
+ errBackhaulStreamsBusy = errors.New("backhaul: stream pool full")
+)
+
+// backhaulStreamAt101 takes a stream slot toward box for the client with
+// clientKey, once the home has answered a hop with 101 Switching Protocols,
+// or counts and logs the refusal and returns the error that fails the hop.
+// The log key is per box, "backhaul-streams-saturated "+box, beside the
+// request pool's "backhaul-saturated "+box.
+func (e *Edge) backhaulStreamAt101(box, eip, clientKey string) (releaseSlot func(), err error) {
+ releaseSlot, ok, shed := e.backhaulAcquireStream(box, clientKey)
+ switch {
+ case shed:
+ e.backhaulShed.fairShare.Add(1)
+ return nil, errBackhaulStreamShare
+ case !ok:
+ e.backhaulShed.streams.Add(1)
+ e.logThrottled("backhaul-streams-saturated "+box,
+ fmt.Sprintf("backhaul to %s (%s) is at its stream cap (%d open WebSockets); answering 503 with Retry-After: 2", box, eip, backhaulMaxStreams.Load()))
+ return nil, errBackhaulStreamsBusy
+ }
+ return releaseSlot, nil
+}
+
// backhaulTransport is the cached outbound transport for one home box. The
// TRANSPORT is what is cached and the ReverseProxy above is what is rebuilt
// per request: a proxy value is two closures, while a transport owns the