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