carlos / platform Public

edge: separate backhaul stream pool so sockets cannot starve requests

An upgraded (WebSocket) hop holds its backhaul slot for the life of the
socket, so long-lived sockets toward one home box filled the single
per-box cap of 64 and every ordinary request to that box got 503.

Upgrade requests (Connection carries the upgrade token and an Upgrade
header is present) now take a slot from a separate stream pool,
CARLOS_BACKHAUL_MAX_STREAMS (default 1024), with its own per-client fair
share of 64 once the pool is half full. The request pool's default rises
from 64 to 256. Both keep count-then-rollback, once-guarded release,
observe and enforce modes, door and tunnel exemption and per-box keys.
Stream saturation is the same 503 + Retry-After 2 and logs under
backhaul-streams-saturated <box>. A far asset fill always takes a
request slot. Refusals are counted in-process (Edge.BackhaulSheds).

Refs #1535
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 442e3958f1f34883e633c30e751c2eef7b9e1591 parent 583fac4
9 files changed, +787 −41
  • internal/edge/asset_far_test.go +2 −0
  • internal/edge/assetcatch.go +4 −1
  • internal/edge/backhaul_holder_export_test.go +5 −1
  • internal/edge/backhaul_share_test.go +3 −0
  • internal/edge/backhaul_streams_test.go +579 −0
  • internal/edge/edge.go +179 −36
  • internal/edge/handover_test.go +5 −3
  • internal/hostenv/hostenv.go +1 −0
  • internal/hostenv/hostenv_test.go +9 −0
diff --git a/internal/edge/asset_far_test.go b/internal/edge/asset_far_test.go
index 00ba7b206..ac9dd5924 100644
--- a/internal/edge/asset_far_test.go
+++ b/internal/edge/asset_far_test.go
@@ -1007,6 +1007,7 @@ func TestBackhaulScrubsTheAssetVocabulary(t *testing.T) {
func TestFarFillShedByTheFairShareIs429(t *testing.T) {
s := newFarScene(t, assetOK(laBody))
s.e.rateMode = RateEnforce
+ backhaulCap(t, 64) // 32 held is half full
req := s.req(http.MethodGet, "/assets/app.js")
key := s.e.backhaulClientKey(req)
if key == "" {
@@ -1334,6 +1335,7 @@ func TestFarLocalAnswersAreRecorded(t *testing.T) {
s := newFarScene(t, assetOK(laBody))
rec := watched(t, s)
s.e.rateMode = RateEnforce
+ backhaulCap(t, 64) // 32 held is half full
req := s.req(http.MethodGet, p)
key := s.e.backhaulClientKey(req)
for i := 0; i < 32; i++ {
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go
index 1b356fcb7..ad8bfd281 100644
--- a/internal/edge/assetcatch.go
+++ b/internal/edge/assetcatch.go
@@ -1290,7 +1290,10 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string
forward()
return true
}
- releaseSlot, ok := e.backhaulAdmit(cw, r, eip, box)
+ // 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)
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 b80ea17cb..1686338dd 100644
--- a/internal/edge/backhaul_holder_export_test.go
+++ b/internal/edge/backhaul_holder_export_test.go
@@ -170,9 +170,13 @@ func (s *BackhaulHolderScene) Upgrade(t *testing.T) {
if resp.StatusCode != 101 {
t.Fatalf("upgrade: %d", resp.StatusCode)
}
- if v, ok := s.sender.edge.backhaulInflight.Load("annie"); !ok || v.(*atomic.Int64).Load() != 0 {
+ // 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 {
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_share_test.go b/internal/edge/backhaul_share_test.go
index 25754429c..d5ae2a080 100644
--- a/internal/edge/backhaul_share_test.go
+++ b/internal/edge/backhaul_share_test.go
@@ -35,6 +35,9 @@ func newShareScene(t *testing.T, mode RateMode) *shareScene {
t.Helper()
e, m, _ := hopEdge(t, "annie", "local.test")
e.rateMode = mode
+ // The arithmetic below is a cap of 64 (half is 32), the default before
+ // #1535 raised it; pinned so the tests read the same.
+ backhaulCap(t, 64)
rec, eip := fakeHomeEdge(t, nil)
homedOn(t, m, "betty", eip, "example.com")
front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/edge/backhaul_streams_test.go b/internal/edge/backhaul_streams_test.go
new file mode 100644
index 000000000..f699fad1c
--- /dev/null
+++ b/internal/edge/backhaul_streams_test.go
@@ -0,0 +1,579 @@
+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.
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// backhaulStreamCap sets the stream pool's cap for one test and restores it
+// after, the seam backhaulCap gives the request pool.
+func backhaulStreamCap(t *testing.T, n int64) {
+ t.Helper()
+ old := backhaulMaxStreams.Load()
+ backhaulMaxStreams.Store(n)
+ t.Cleanup(func() { backhaulMaxStreams.Store(old) })
+}
+
+func poolCount(m *sync.Map, box string) int64 {
+ v, ok := m.Load(box)
+ if !ok {
+ return 0
+ }
+ 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)
+ }
+ return r
+}
+
+func TestBackhaulUpgradeClassification(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ conn []string
+ upgrade []string
+ want bool
+ }{
+ {"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},
+ } {
+ 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)
+ }
+ }
+}
+
+// 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)
+ }
+ if defaultBackhaulMaxStreams != 1024 {
+ t.Fatalf("defaultBackhaulMaxStreams = %d, want 1024", defaultBackhaulMaxStreams)
+ }
+ if backhaulStreamClientShare != 64 {
+ t.Fatalf("backhaulStreamClientShare = %d, want 64", backhaulStreamClientShare)
+ }
+}
+
+// The stream knob follows the request knob's rules: unset, unparseable and
+// non-positive all mean the default, never uncapped and never zero.
+func TestBackhaulMaxStreamsFromEnv(t *testing.T) {
+ const name = "CARLOS_BACKHAUL_MAX_STREAMS"
+ ambient, had := os.LookupEnv(name)
+ t.Cleanup(func() {
+ if had {
+ os.Setenv(name, ambient)
+ return
+ }
+ os.Unsetenv(name)
+ })
+ for _, tc := range []struct {
+ set bool
+ raw string
+ want int
+ }{
+ {set: false, want: defaultBackhaulMaxStreams},
+ {set: true, raw: "", want: defaultBackhaulMaxStreams},
+ {set: true, raw: " ", want: defaultBackhaulMaxStreams},
+ {set: true, raw: "lots", want: defaultBackhaulMaxStreams},
+ {set: true, raw: "0", want: defaultBackhaulMaxStreams},
+ {set: true, raw: "-1", want: defaultBackhaulMaxStreams},
+ {set: true, raw: "4096", want: 4096},
+ {set: true, raw: " 16 ", want: 16},
+ } {
+ if tc.set {
+ t.Setenv(name, tc.raw)
+ } else {
+ os.Unsetenv(name)
+ }
+ if got := backhaulStreamsFromEnv(); got != tc.want {
+ t.Fatalf("%s=%q (set=%v) → %d, want %d", name, tc.raw, tc.set, got, tc.want)
+ }
+ }
+}
+
+// Streams filling their pool take nothing from the request pool, and the
+// request pool full takes nothing from the stream pool.
+func TestBackhaulPoolsAreSeparate(t *testing.T) {
+ e, _, _ := hopEdge(t, "annie", "local.test")
+ backhaulCap(t, 2)
+ backhaulStreamCap(t, 3)
+ for i := 0; i < 3; i++ {
+ rel, ok, shed := e.backhaulAcquireStream("betty", "")
+ if !ok || shed {
+ t.Fatalf("stream %d: ok=%v shed=%v", i+1, ok, shed)
+ }
+ t.Cleanup(rel)
+ }
+ if _, ok, _ := e.backhaulAcquireStream("betty", ""); ok {
+ t.Fatal("a fourth stream was admitted over a cap of 3")
+ }
+ for i := 0; i < 2; i++ {
+ rel, ok, _ := e.backhaulAcquire("betty", "")
+ if !ok {
+ t.Fatalf("request %d refused while only streams were held", i+1)
+ }
+ t.Cleanup(rel)
+ }
+ if _, ok, _ := e.backhaulAcquire("betty", ""); ok {
+ t.Fatal("a third request was admitted over a cap of 2")
+ }
+ if got := poolCount(&e.backhaulInflight, "betty"); got != 2 {
+ t.Fatalf("request pool = %d, want 2", got)
+ }
+ if got := poolCount(&e.backhaulStreamInflight, "betty"); got != 3 {
+ t.Fatalf("stream pool = %d, want 3", got)
+ }
+}
+
+// One client opening many sockets is refused its share of a busy stream
+// pool while another client still gets streams. Requests are not affected.
+func TestBackhaulStreamShare(t *testing.T) {
+ e, _, _ := hopEdge(t, "annie", "local.test")
+ e.rateMode = RateEnforce
+ backhaulStreamCap(t, 128)
+ const a, b = "203.0.113.1/32", "203.0.113.2/32"
+ for i := 0; i < backhaulStreamClientShare; i++ {
+ rel, ok, shed := e.backhaulAcquireStream("betty", a)
+ if !ok || shed {
+ t.Fatalf("A's stream %d: ok=%v shed=%v", i+1, ok, shed)
+ }
+ t.Cleanup(rel)
+ }
+ 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)
+ }
+ rel, ok, shed := e.backhaulAcquireStream("betty", b)
+ if !ok || shed {
+ t.Fatalf("B: ok=%v shed=%v, want a stream", ok, shed)
+ }
+ rel()
+ rel, ok, shed = e.backhaulAcquire("betty", a)
+ if !ok || shed {
+ t.Fatalf("A's ordinary request: ok=%v shed=%v, want the request pool's slot", ok, shed)
+ }
+ rel()
+}
+
+// Under half full, the stream share takes no part.
+func TestBackhaulStreamShareQuiet(t *testing.T) {
+ e, _, _ := hopEdge(t, "annie", "local.test")
+ e.rateMode = RateEnforce
+ backhaulStreamCap(t, 1024)
+ for i := 0; i < backhaulStreamClientShare+10; i++ {
+ rel, ok, shed := e.backhaulAcquireStream("betty", "203.0.113.1/32")
+ if !ok || shed {
+ t.Fatalf("stream %d under half full: ok=%v shed=%v", i+1, ok, shed)
+ }
+ t.Cleanup(rel)
+ }
+}
+
+// Observe mode logs the refusal and admits; off takes no part.
+func TestBackhaulStreamShareModes(t *testing.T) {
+ for _, mode := range []RateMode{RateObserve, RateOff} {
+ e, _, _ := hopEdge(t, "annie", "local.test")
+ e.rateMode = mode
+ 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)
+ }
+ t.Cleanup(rel)
+ }
+ logged := strings.Contains(buf.String(), "would refuse")
+ if logged != (mode == RateObserve) {
+ t.Fatalf("mode %v: \"would refuse\" logged = %v: %s", mode, logged, buf.String())
+ }
+ if got := e.BackhaulSheds(); got != (BackhaulSheds{}) {
+ t.Fatalf("mode %v counted sheds %+v, want none: nothing was refused", mode, got)
+ }
+ }
+}
+
+// Every slot and share of both pools comes back, once, however often
+// release is called.
+func TestBackhaulPoolsReleaseOnce(t *testing.T) {
+ e, _, _ := hopEdge(t, "annie", "local.test")
+ e.rateMode = RateEnforce
+ const key = "198.51.100.7/32"
+ var rels []func()
+ for i := 0; i < 8; i++ {
+ for _, acquire := range []func(string, string) (func(), bool, bool){e.backhaulAcquire, e.backhaulAcquireStream} {
+ rel, ok, shed := acquire("betty", key)
+ if !ok || shed {
+ t.Fatalf("slot %d: ok=%v shed=%v", i+1, ok, shed)
+ }
+ rels = append(rels, rel)
+ }
+ }
+ for _, rel := range rels {
+ rel()
+ rel()
+ }
+ for name, m := range map[string]*sync.Map{"request": &e.backhaulInflight, "stream": &e.backhaulStreamInflight} {
+ if got := poolCount(m, "betty"); got != 0 {
+ t.Fatalf("%s pool = %d after every release, want 0", name, got)
+ }
+ }
+ for name, m := range map[string]*sync.Map{"request": &e.backhaulShares, "stream": &e.backhaulStreamShares} {
+ sv, _ := m.Load("betty")
+ if got := sv.(interface{ Held(string) int }).Held(key); got != 0 {
+ t.Fatalf("client still holds %d %s share(s) after every release", got, name)
+ }
+ }
+}
+
+// Concurrent streams never exceed the stream cap and drift nothing; run
+// under -race.
+func TestBackhaulStreamsConcurrent(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()
+ }
+ }
+ }()
+ }
+ wg.Wait()
+ if got := poolCount(&e.backhaulStreamInflight, "betty"); got != 0 {
+ t.Fatalf("stream pool = %d at rest, want 0", got)
+ }
+}
+
+// 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) {
+ e, _, _ := hopEdge(t, "annie", "local.test")
+ e.rateMode = RateEnforce
+ backhaulCap(t, 1)
+ backhaulStreamCap(t, 128)
+ buf := captureLog(t)
+
+ plain := 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")
+ }
+ 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"))
+ }
+
+ // 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")
+ if !ok {
+ t.Fatalf("A's socket %d refused with the request pool full", 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 {
+ 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")
+ }
+ 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"))
+ }
+
+ if got, want := e.BackhaulSheds(), (BackhaulSheds{Requests: 1, Streams: 1, FairShare: 1}); 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") {
+ 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)
+ }
+}
+
+// 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 {
+ t.Helper()
+ stop := make(chan struct{})
+ t.Cleanup(func() { close(stop) })
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Upgrade") == "" {
+ fmt.Fprint(w, homeEdgeBody)
+ return
+ }
+ if reject {
+ http.Error(w, "no sockets here", http.StatusBadRequest)
+ 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")
+ if buf.Flush() != nil {
+ return
+ }
+ go func() { <-stop; conn.Close() }()
+ for {
+ line, err := buf.ReadString('\n')
+ if err != nil {
+ return
+ }
+ buf.WriteString("home:" + line)
+ if buf.Flush() != nil {
+ return
+ }
+ }
+ })
+}
+
+// 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) {
+ t.Helper()
+ c, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://"))
+ if err != nil {
+ t.Fatalf("dial edge: %v", err)
+ }
+ t.Cleanup(func() { c.Close() })
+ 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 {
+ t.Fatalf("write handshake: %v", err)
+ }
+ br := bufio.NewReader(c)
+ resp, err := http.ReadResponse(br, nil)
+ if err != nil {
+ t.Fatalf("read handshake response: %v", err)
+ }
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ return nil, resp
+ }
+ if _, err := fmt.Fprint(c, "ping\n"); err != nil {
+ t.Fatalf("write frame: %v", err)
+ }
+ if line, err := br.ReadString('\n'); err != nil || line != "home:ping\n" {
+ t.Fatalf("echo = %q (%v), want home:ping", line, err)
+ }
+ return c, resp
+}
+
+// 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.
+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))
+ homedOn(t, m, "betty", eip, "example.com")
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ get := backhaulGetter(t, e)
+
+ var socks []net.Conn
+ for i := 0; i < n+1; i++ {
+ c, resp := openBackhaulSocket(t, srv)
+ if c == nil {
+ t.Fatalf("socket %d refused: %d", i+1, resp.StatusCode)
+ }
+ socks = append(socks, c)
+ }
+ if got := poolCount(&e.backhaulStreamInflight, "betty"); got != n+1 {
+ 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)
+ }
+ for i := 0; i < 2*n; i++ {
+ resp, err := get("example.com")
+ if err != nil {
+ t.Fatalf("GET %d: %v", i+1, err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusOK || string(body) != homeEdgeBody {
+ t.Fatalf("GET %d with %d sockets open: %d %q, want the home's 200", i+1, n+1, resp.StatusCode, body)
+ }
+ }
+
+ 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)
+ }
+ if got := e.BackhaulSheds(); got.Streams != 1 || got.Requests != 0 {
+ t.Fatalf("BackhaulSheds = %+v, want one stream shed", got)
+ }
+
+ 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 {
+ 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) {
+ e, m, _ := hopEdge(t, "annie", "local.test")
+ backhaulCap(t, 1)
+ _, eip := fakeHomeEdge(t, wsHome(t, false))
+ 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)
+ }
+ 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"))
+ }
+ if c, resp := openBackhaulSocket(t, srv); c == nil {
+ t.Fatalf("socket with the request pool full: %d, want 101", resp.StatusCode)
+ }
+}
+
+// An upgrade request the home answers without switching protocols still
+// gives its stream slot back when the hop ends.
+func TestBackhaulRefusedUpgradeReleasesStreamSlot(t *testing.T) {
+ e, m, _ := hopEdge(t, "annie", "local.test")
+ _, eip := fakeHomeEdge(t, wsHome(t, true))
+ 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)
+ }
+ waitFor(t, 10*time.Second, "the stream slot back", func() bool {
+ return poolCount(&e.backhaulStreamInflight, "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)
+ }
+}
+
+// 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)
+ }
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 7bb926a7b..f6fe1ad4c 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -68,6 +68,7 @@ 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
@@ -444,6 +445,15 @@ type Edge struct {
// holds, for the fair share in backhaulAcquire. Keyed by box for the
// reason backhaulInflight is; each Shares bounds its own client keys.
backhaulShares sync.Map // box → *ratelimit.Shares
+ // backhaulStreamInflight and backhaulStreamShares are the same pair for
+ // the stream pool: the slots upgrade requests (WebSockets) take, held
+ // for the life of the socket (backhaulAcquireStream). Keyed by box for
+ // the same reason.
+ backhaulStreamInflight sync.Map // box → *atomic.Int64
+ backhaulStreamShares sync.Map // box → *ratelimit.Shares
+ // backhaulShed counts the hops backhaulAdmit refused, by kind, since
+ // this edge started (BackhaulSheds).
+ backhaulShed struct{ requests, streams, fairShare atomic.Uint64 }
// bodyReads counts, per client, the request bodies this edge is still
// waiting on (readBoundedBody), built on first use. Its own Shares, not
// a box's: the wait happens before any hop is admitted.
@@ -4678,9 +4688,16 @@ func fleetProxy(fleet, boxLabel string, authoritative bool, hub *TunnelHub) *htt
// its edges file.
// backhaulMaxInflight is the containment ruling of 2026-08-24: at most this
-// many backhauled requests may be in flight toward any ONE home box at a
-// time, counted on the SENDING edge. At the limit the sender answers 503 +
-// Retry-After: 2 (backhaul, below) rather than dialling.
+// many backhauled request/response hops may be in flight toward any ONE home
+// 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
+// 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.
//
// A concurrency bound and not a rate: cross-region egress is (concurrent
// streams × per-stream bandwidth), so a request-rate cap would neither bound
@@ -4692,7 +4709,9 @@ func fleetProxy(fleet, boxLabel string, authoritative bool, hub *TunnelHub) *htt
// Sender-side because every backhauled byte traverses BOTH legs (home →
// sender, sender → client), so one cap here bounds both boxes' egress at
// once; the home box needs no twin, its inbound hops being bounded by the sum
-// of its siblings' caps.
+// of its siblings' caps. With two pools that bound is the sum of both pools
+// over every sibling: at most backhaulMaxInflight + backhaulMaxStreams hops
+// from each sending edge toward any one box.
//
// A var, not a const, so a test can shorten it — the same reason backhaulPort
// is one. There is deliberately no "off" value: an unbounded cross-region
@@ -4704,22 +4723,54 @@ 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 = 64
+const defaultBackhaulMaxInflight = 256
-func init() { backhaulMaxInflight.Store(defaultBackhaulMaxInflight) }
+// 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.
+//
+// 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.
+//
+// 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.
+var backhaulMaxStreams atomic.Int64
+
+const defaultBackhaulMaxStreams = 1024
+
+func init() {
+ backhaulMaxInflight.Store(defaultBackhaulMaxInflight)
+ backhaulMaxStreams.Store(defaultBackhaulMaxStreams)
+}
// backhaulInflightFromEnv reads CARLOS_BACKHAUL_MAX_INFLIGHT. Unset,
// unparseable or ≤ 0 all mean the default: a typo'd knob must not silently
// uncap (or, worse, zero-cap) a deployment's backhaul.
func backhaulInflightFromEnv() int {
- raw := strings.TrimSpace(os.Getenv("CARLOS_BACKHAUL_MAX_INFLIGHT"))
+ return backhaulCapFromEnv("CARLOS_BACKHAUL_MAX_INFLIGHT", defaultBackhaulMaxInflight, "concurrent backhauled requests per home box")
+}
+
+// backhaulStreamsFromEnv reads CARLOS_BACKHAUL_MAX_STREAMS, by
+// backhaulInflightFromEnv's rules.
+func backhaulStreamsFromEnv() int {
+ return backhaulCapFromEnv("CARLOS_BACKHAUL_MAX_STREAMS", defaultBackhaulMaxStreams, "open backhauled WebSockets per home box")
+}
+
+func backhaulCapFromEnv(name string, def int, what string) int {
+ raw := strings.TrimSpace(os.Getenv(name))
if raw == "" {
- return defaultBackhaulMaxInflight
+ return def
}
n, err := strconv.Atoi(raw)
if err != nil || n <= 0 {
- log.Printf("edge: CARLOS_BACKHAUL_MAX_INFLIGHT=%q is not a positive integer — using the default of %d concurrent backhauled requests per home box", raw, defaultBackhaulMaxInflight)
- return defaultBackhaulMaxInflight
+ log.Printf("edge: %s=%q is not a positive integer — using the default of %d %s", name, raw, def, what)
+ return def
}
return n
}
@@ -4729,9 +4780,28 @@ func backhaulInflightFromEnv() int {
// setting: the sending edge has no route row to read one from (#358).
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.
+const backhaulStreamClientShare = 64
+
// 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,
@@ -4750,12 +4820,32 @@ func (e *Edge) backhaulClientKey(r *http.Request) string {
return p.String()
}
-// backhaulAcquire reserves one in-flight slot toward box, or reports why it
-// cannot: saturation (ok and shed both false, the box's cap is spent) or a
+// backhaulPool is one of a box's two pools: where its counts live, its cap
+// and fair share, and the names its log lines use.
+type backhaulPool struct {
+ inflight, shares *sync.Map
+ limit int64
+ share int
+ logKey string // throttle key prefix for a share refusal
+ slots string // what the log line calls the pool's slots
+}
+
+func (e *Edge) requestPool() backhaulPool {
+ return backhaulPool{&e.backhaulInflight, &e.backhaulShares, backhaulMaxInflight.Load(), backhaulClientShare,
+ "backhaul-share ", "slots"}
+}
+
+func (e *Edge) streamPool() backhaulPool {
+ return backhaulPool{&e.backhaulStreamInflight, &e.backhaulStreamShares, backhaulMaxStreams.Load(), backhaulStreamClientShare,
+ "backhaul-streams-share ", "stream slots"}
+}
+
+// backhaulAcquire reserves one request-pool slot toward box, or reports why
+// it cannot: saturation (ok and shed both false, the box's cap is spent) or a
// fair-share refusal (shed true). releaseSlot must be called exactly once
-// when the hop's ServeHTTP returns — a streaming or upgraded response holds
-// its slot for the life of the stream, deliberately: a long-lived stream IS
-// sustained cross-region egress, which is the thing being bounded.
+// when the hop's ServeHTTP returns — a streaming response holds its slot for
+// the life of the stream, deliberately: a long-lived stream IS sustained
+// cross-region egress, which is the thing being bounded.
//
// The fair share is the home edge's rule over the sending edge's slots: while
// the box's slots are at least half taken, a client that already holds
@@ -4774,16 +4864,27 @@ func (e *Edge) backhaulClientKey(r *http.Request) string {
// cross-region bytes the cap exists to prevent. A fair-share refusal rolls
// the count back the same way.
func (e *Edge) backhaulAcquire(box, clientKey string) (releaseSlot func(), ok bool, shed bool) {
+ 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.
+func (e *Edge) backhaulAcquireStream(box, clientKey string) (releaseSlot func(), ok bool, shed bool) {
+ return e.acquirePoolSlot(e.streamPool(), box, clientKey)
+}
+
+func (e *Edge) acquirePoolSlot(p backhaulPool, box, clientKey string) (releaseSlot func(), ok bool, shed bool) {
// Load first, like backhaulTransport: LoadOrStore would allocate a
// counter per backhauled request just to throw it away on the hit path.
- v, hit := e.backhaulInflight.Load(box)
+ v, hit := p.inflight.Load(box)
if !hit {
- v, _ = e.backhaulInflight.LoadOrStore(box, new(atomic.Int64))
+ v, _ = p.inflight.LoadOrStore(box, new(atomic.Int64))
}
n := v.(*atomic.Int64)
- limit := backhaulMaxInflight.Load()
held := n.Add(1)
- if held > limit {
+ if held > p.limit {
n.Add(-1)
return nil, false, false
}
@@ -4793,27 +4894,27 @@ func (e *Edge) backhaulAcquire(box, clientKey string) (releaseSlot func(), ok bo
var once sync.Once
var releaseShare func()
if clientKey != "" && e.rateMode != RateOff {
- sv, hit := e.backhaulShares.Load(box)
+ sv, hit := p.shares.Load(box)
if !hit {
- sv, _ = e.backhaulShares.LoadOrStore(box, ratelimit.NewShares(backhaulSharesMaxKeys))
+ sv, _ = p.shares.LoadOrStore(box, ratelimit.NewShares(backhaulSharesMaxKeys))
}
shares := sv.(*ratelimit.Shares)
// Busy is the slots already taken, not counting this request.
- busy := held-1 >= limit/2
- rel, admitted := shares.Acquire(clientKey, busy, backhaulClientShare)
+ busy := held-1 >= p.limit/2
+ rel, admitted := shares.Acquire(clientKey, busy, p.share)
if !admitted {
verb := "refused"
if e.rateMode == RateObserve {
verb = "would refuse"
}
- e.logThrottled("backhaul-share "+box, fmt.Sprintf(
- "backhaul to %s is at least half full (%d of %d slots) and client %s holds %d of them — %s the request (fair share %d)",
- box, held-1, limit, clientKey, shares.Held(clientKey), verb, backhaulClientShare))
+ 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)",
+ box, held-1, p.limit, p.slots, clientKey, shares.Held(clientKey), verb, p.share))
if e.rateMode == RateEnforce {
n.Add(-1)
return nil, false, true
}
- rel, _ = shares.Acquire(clientKey, false, backhaulClientShare)
+ rel, _ = shares.Acquire(clientKey, false, p.share)
}
releaseShare = rel
}
@@ -4827,6 +4928,26 @@ func (e *Edge) backhaulAcquire(box, clientKey string) (releaseSlot func(), ok bo
}, true, false
}
+// 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.
+type BackhaulSheds struct {
+ Requests uint64
+ Streams uint64
+ FairShare uint64
+}
+
+// BackhaulSheds reads the counters. In-process atomics only: no store read.
+func (e *Edge) BackhaulSheds() BackhaulSheds {
+ return BackhaulSheds{
+ Requests: e.backhaulShed.requests.Load(),
+ Streams: e.backhaulShed.streams.Load(),
+ FairShare: e.backhaulShed.fairShare.Load(),
+ }
+}
+
// backhaulPort is the port a home edge answers on. Always 443 in production —
// an edges file publishes a bare EIP (Task 1) and every edge's front door is
// 443 — and a var only so a test can point the dial at an httptest server, the
@@ -4943,32 +5064,53 @@ 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
-// (backhaulAcquire with backhaulClientKey), or answers the refusal on w and
-// reports false. It is the one place both refusals are written, for an
-// ordinary hop (backhaulTo) and for a far asset fill (serveAssetFar).
+// 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).
//
// 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, 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 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.
//
// 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) {
- releaseSlot, ok, shed := e.backhaulAcquire(box, e.backhaulClientKey(r))
+ 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))
if shed {
// The fair share, not saturation: this client holds its share of a
// busy hop. The same 429 the home edge gives (writeRateLimited).
+ e.backhaulShed.fairShare.Add(1)
writeRateLimited(w, time.Second)
return nil, false
}
if !ok {
- 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()))
+ 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()))
+ }
Unavailable(w, "backhaul-busy", "temporarily busy", 2)
return nil, false
}
@@ -5231,6 +5373,7 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
// than per request (backhaulMaxInflight). Inert on a single-box
// deployment, where nothing is ever backhauled at all.
backhaulMaxInflight.Store(int64(backhaulInflightFromEnv()))
+ backhaulMaxStreams.Store(int64(backhaulStreamsFromEnv()))
// GeoIP (geoip spec §5.1): a tunnel client takes the hub's answer and
// mirrors nothing; an edge with the deployment store mirrors; anything
diff --git a/internal/edge/handover_test.go b/internal/edge/handover_test.go
index 61b92910b..27ec084c8 100644
--- a/internal/edge/handover_test.go
+++ b/internal/edge/handover_test.go
@@ -591,12 +591,14 @@ func TestHandoverExitOnUnfinishedBodies(t *testing.T) {
}
}
-// hoCap puts every hop at its admission cap.
+// hoCap puts every hop at its admission cap: both pools, since an upgrade
+// request takes a stream slot (#1535).
func hoCap(t *testing.T) {
t.Helper()
- old := backhaulMaxInflight.Load()
+ old, oldStreams := backhaulMaxInflight.Load(), backhaulMaxStreams.Load()
backhaulMaxInflight.Store(0)
- t.Cleanup(func() { backhaulMaxInflight.Store(old) })
+ backhaulMaxStreams.Store(0)
+ t.Cleanup(func() { backhaulMaxInflight.Store(old); backhaulMaxStreams.Store(oldStreams) })
}
// hoUnreachable makes every forward dial fail at once, as a refused
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go
index ad540ef08..c2bcbee5d 100644
--- a/internal/hostenv/hostenv.go
+++ b/internal/hostenv/hostenv.go
@@ -86,6 +86,7 @@ var Optional = []string{
"CARLOS_ALERT_MEM_PCT",
"CARLOS_AWS_REGION",
"CARLOS_BACKHAUL_MAX_INFLIGHT",
+ "CARLOS_BACKHAUL_MAX_STREAMS",
"CARLOS_CHANGE_INDEX",
"CARLOS_DEMO_API_CONSOLE_ORIGIN",
"CARLOS_DEMO_API_ORIGIN",
diff --git a/internal/hostenv/hostenv_test.go b/internal/hostenv/hostenv_test.go
index 42715167f..24e8d49af 100644
--- a/internal/hostenv/hostenv_test.go
+++ b/internal/hostenv/hostenv_test.go
@@ -875,3 +875,12 @@ func TestGenerationsSwitchHostEnv(t *testing.T) {
})
}
}
+
+// Both backhaul pool caps (#1535) may be delivered to a box's host.env.
+func TestBackhaulPoolCapsAllowed(t *testing.T) {
+ for _, k := range []string{"CARLOS_BACKHAUL_MAX_INFLIGHT", "CARLOS_BACKHAUL_MAX_STREAMS"} {
+ if !Allowed(k) {
+ t.Errorf("%s is not allowed in host.env", k)
+ }
+ }
+}