edge: maximum load, hub restart and two Reloads over open sockets (#471 Task 7)
Three witnesses over Task 6's production-wired scene, each in the trusted
child (internal/edge/tunnel_ws_load_e2e_test.go):
- TestTunnelWebSocketMaximumLoad, spec §8.2 case 13. Production values
(DefaultLimits, cap 128), scaled under -short (Limits{16, 64 KiB,
768 KiB}, cap 8). The cap's worth of sockets have app sides that never
read. Each client is pushed back by a 500 ms write deadline, and what
it handed over beyond the kernel's TCP queues is held to StreamWindow
+ 4 MiB. The next handshake gets 503 Retry-After 5 with tunnel_busy.
100 (7) held GETs all arrive and complete. A 16 MiB (512 KiB) POST
completes within 10 s with its SHA-256 intact. Every socket closes, the
count returns to 0, and a new upgrade gets 101.
- TestTunnelWebSocketHubRestart, case 9. processDeath closes the
listener and every accepted conn. Both ends close within 2 s. A new
hub over the same registry on the same address gets the box's
re-registration within 3 s, and a new socket gets 101.
listenerShutdownOnly runs Server.Shutdown alone, and the open socket
keeps echoing.
- TestTunnelWebSocketTwoReloads, case 18 with sockets. Task 4's schedule
is decided by TryLock and the exact event log, and both endpoints'
recorded closes are judged against one deadline taken at the sweep's
trigger. Items 8 (B fails) and 9 (reversed) are sub-tests.
The scene gains wsOpts (box limits, hub cap, an app wrapper), and the hub
is built and served by newHub and serveHub so the restart can make a
second one. Task 6's callers are migrated to newWSScene(t, fx, wsOpts{}).
A load.example.com forward row raises busy_at, so 100 held GETs from one
client measure stream slots, not the rate limit.
On Linux the spec's "StreamWindow + 4 MiB of kernel buffers" does not
hold as written: autotuning grows the client's send queue to tcp_wmem
(4 MiB) and the hub's receive queue toward tcp_rmem (6 MiB), nearly
10 MiB per socket on loopback. So the queues (SIOCOUTQ + SIOCINQ) are
measured and taken off, and the rest is held to the bound.
Production-values run (nice 19, a prebuilt test binary): PASS, wall
1.6 s, peak RSS 261 MiB (the trusted child). 128 sockets pushed back
after 1.28 to 1.35 MiB beyond the TCP queues, and the 16 MiB POST took
37 ms.
Mutations killed: conn window = stream window (the POST times out after
10 s), half the stream slots (0 of 7 GETs arrive), no push-back, an
8 MiB stream buffer, Server.Close as "death", no redial, closeAll
before Shutdown, no reloadMu (TryLock), sweep before publish, and
baselining a failed Reload.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/edge/tunnel_ws_e2e_test.go+133 −64internal/edge/tunnel_ws_load_e2e_test.go+818 −0
Intent
<task-notification> <task-id>a58070cdd3a43a333</task-id> <tool-use-id>toolu_01XM5Dz13e2d1UxxrL7x5Gwv</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a58070cdd3a43a333.output</output-file> <status>completed</status> <summary>Agent "#471 Task 6: production-wired witness" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE_WITH_CONCERNS **Commit:** `070433f0` on `design-tunnel-websockets-471`, on top of `12e5531d`. Not pushed. **Tests:** the login, gate, door, forward and e2e tests pass under `-race` with no data races. The darwin, windows and linux/arm64 builds and vet pass, and the census card is unchanged (seal `1379d066…5e7`). The kept login body is now read under a deadline: a new constant, `loginBodyTimeout`, set to 10 s because the gate has no body timeout to reuse. A package variable lets the tests shorten it, and the deadline is cleared once the body is in. A writer that cannot set deadlines reads as before, and the comment says what that covers. The edge only serves on Go's standard HTTP servers, whose writers support deadlines, so in practice that means a test recorder. - **Test first:** the new stalled-body test sends the headers and 5 bytes of the form, then nothing. Before the fix it got no answer within 5 s. Now it gets a 413 in about 0.3 s, over both HTTP/1 and HTTP/2 on TLS, and nothing reaches the box. Removing the deadline makes it fail again. - **Pass-through not cut off:** a login passed down the tunnel whose box answers well after the deadline is still answered, and the same connection serves a second request. - **One fix beyond the brief:** a failed read keeps the deadline expired and adds `Connection: close` to the 413. Clearing the deadline on every path still hung: Go's HTTP server tries to read the rest of an unread body before writing the answer, and that waited on the client again. **Concerns:** - **Two mutations survive, both equivalent.** Never clearing the deadline changes nothing visible: over HTTP/1 Go's server clears it itself once the body is read, and over HTTP/2 the deadline is on a stream whose body is already complete. I kept the clear because the ruling asks for it. Clearing before the error check also changes nothing, because `Connection: close` alone stops that read of the rest of the body; the expired deadline is a second guard. - **One wall-clock wait in the pass-through test.** It has to let the deadline pass, since the deadline is what is being tested; it is commented. The fix report is appended to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-tunnel-websockets-471/.superpowers/sdd/2026-10-30-tunnel-websockets/task-6-report.md`. Scratch is removed and no processes are left running.</result> <usage><subagent_tokens>442799</subagent_tokens><tool_uses>15</tool_uses><duration_ms>579846</duration_ms></usage> </task-notification>
<task-notification> <task-id>a3be5845734ab5e17</task-id> <tool-use-id>toolu_01XJEteuQiFZWg9S9MFSdR2Q</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a3be5845734ab5e17.output</output-file> <status>completed</status> <summary>Agent "Plan 6 Task 7a: carlos run on rootfs" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE_WITH_CONCERNS **Commit:** `a76ab51c` on rootfs-apps-6-interactive (not pushed). The full report is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-apps-6/.superpowers/sdd/2026-10-24-rootfs-apps-6-interactive/task-7a-report.md`. **Tests:** all the brief's Step 2 and Step 4 selections pass for activator, instancectl, console, host, provision, the root package and docsite. The invariant guards (INV-1, INV-2, INV-4, INV-5, `rootfsSeamInterfaces`, the four removal guards) pass and only grew. The darwin, windows and linux/arm64 builds are clean. 32 of 32 mutations were killed, among them removing the kill at lease loss (M1) and removing the second kill for a start in flight (M2). **Census:** the root-read overlay rootfs-apps-6 is re-proposed with seal `a4237374…`. The 17 earlier claims carry over unchanged, and this task adds 17. The record-write census re-pins `runsWorker.finish`. I did not request approval. **Concerns:** 1. `TestRootfsRunPollsAndStopsTheRootfsUnit`, and the arm64 half of `TestRootfsRunRunsArgsInTheImage`, skip on this amd64 box, so they have not run in this task. They will run on CI's arm64 worker. 2. The new lease tests use real-time windows of 0.4 to 1.5 seconds, as the existing resident lease tests do. Each passed, but they could be timing-sensitive under heavy load. 3. One root-side choice beyond the brief: if a kill succeeds but the cleanup afterwards can't prove the unit gone, root now answers `statusGenUnproven` instead of 502. That answer couldn't happen before, because kill was refused for these roles, and it keeps the client's `ErrGenUnproven` typing consistent. Mutation M26 pins it. 4. The 400 message "kill=1 belongs to a generation stop only" is kept word for word, as the brief says, though a rootfs cmd or tty stop now accepts kill too. 5. Two existing tests changed to match the new rules: the cmd row of `TestRootfsRowsNeverTakeABinaryLaunch`, and `TestRunInterruptedWhileItsStopIsRetriedEndsAt125`, which now expects the run directory to stay. 6. Some `go vet` runs on darwin and windows fail in test files this task didn't touch: `activator_test.go:4930` (`unix.Mkfifo`) and `host/hawake_wiring_test.go:34` (`claimsOnEnv`). The builds themselves are clean. 7. Test-first only partly held. The run path (`StartCmd` and `startRootfsRun`) and `AfterSettled` in `cmd.go` were written before their tests. Their failing state is shown by mutations rather than by a run before the code existed. The lease, root, console and box changes had their tests written first and seen failing. All scratch files are deleted and nothing I started is still running.</result> <usage><subagent_tokens>526947</subagent_tokens><tool_uses>163</tool_uses><duration_ms>3305069</duration_ms></usage> </task-notification>
Attributed to this commit: 4.51 g CO₂e (526,213 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-tunnel-websockets-471, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/edge/tunnel_ws_e2e_test.go b/internal/edge/tunnel_ws_e2e_test.go| index 182a183b1..4991fb931 100644 |
| --- a/internal/edge/tunnel_ws_e2e_test.go |
| +++ b/internal/edge/tunnel_ws_e2e_test.go |
| @@ -35,6 +35,7 @@ package edge |
| import ( |
| "bufio" |
| "context" |
| + "crypto/ed25519" |
| "crypto/rand" |
| "crypto/sha1" |
| "crypto/tls" |
| @@ -75,6 +76,7 @@ const ( |
| wsRawHost = "raw.example.com" // forward row the box answers by hand |
| wsOldHost = "old.example.com" // forward row on away, for the old box |
| wsOtherHost = "other.example.com" // a host case 16 changes |
| + wsLoadHost = "load.example.com" // forward row on home, ungated, for the load test (Task 7) |
| cableProtocol = "actioncable-v1-json" |
| cableChannel = `{"channel":"TestChannel"}` |
| @@ -82,6 +84,10 @@ const ( |
| wsWideRate = `{"rate":1,"burst":100000}` // never in the way |
| wsLimitedRate = `{"rate":1,"burst":2}` // the hub's: two, then 429 |
| wsBoxRate = `{"rate":1,"burst":1}` // the box's own row, never judged |
| + // wsLoadRate never sheds: the load test's 100 held GETs come from one |
| + // client, past the default busy_at of 64 and client share of 16. The |
| + // test is about the tunnel's stream slots, not the rate limit. |
| + wsLoadRate = `{"rate":1,"burst":100000,"busy_at":100000}` |
| wsBox1 = "home/box-1" |
| wsBox2 = "away/box-2" |
| @@ -457,8 +463,24 @@ const ( |
| // ---- the scene ------------------------------------------------------------- |
| +// wsOpts is the scene's shape. The zero value is Task 6's scene: the |
| +// production limits on the box's loops and the production cap at the hub. |
| +type wsOpts struct { |
| + // limits are the box loops' HTTP/2 limits (Config.Limits); nil is |
| + // tunnelclient.DefaultLimits. |
| + limits *tunnelclient.Limits |
| + // upgradeCap is the hub's cap per channel connection; 0 is |
| + // tunnelUpgradeCap. |
| + upgradeCap int |
| + // app, when set, wraps the app's handler (the load test's paths). |
| + app func(http.Handler) http.Handler |
| +} |
| + |
| type wsScene struct { |
| t *testing.T |
| + fx tlsFixture |
| + opts wsOpts |
| + pub ed25519.PublicKey |
| hub, box *Edge |
| hubReg, boxReg *registry.Registry |
| srv, wrapSrv *httptest.Server |
| @@ -474,8 +496,9 @@ type wsScene struct { |
| throttle atomic.Bool // the plan throttle hook's answer for fwdOwner |
| inserts atomic.Int64 |
| - inserted chan *upgradeReservation // each reservation, as it is taken |
| - noted map[*upgradeReservation]bool // guarded by hub.open.mu |
| + inserted chan *upgradeReservation // each reservation, as it is taken |
| + notedMu sync.Mutex |
| + noted map[*upgradeReservation]bool // guarded by notedMu |
| // the wrapping server's mode and the barrier its handler waits on |
| // after the hub returns (case 12) |
| @@ -490,9 +513,9 @@ type wsScene struct { |
| cookies map[string]string |
| } |
| -// newWSScene builds the scene and starts the box's loops as home/box-1 |
| -// and t1. It does not wait for them to connect. |
| -func newWSScene(t *testing.T, fx tlsFixture) *wsScene { |
| +// newWSScene builds the scene in opts' shape and starts the box's loops |
| +// as home/box-1 and t1. It does not wait for them to connect. |
| +func newWSScene(t *testing.T, fx tlsFixture, opts wsOpts) *wsScene { |
| t.Helper() |
| // The hub's environment, read by New and Reload; set first. |
| t.Setenv("CARLOS_TUNNEL_HOST", "127.0.0.1") |
| @@ -504,7 +527,7 @@ func newWSScene(t *testing.T, fx tlsFixture) *wsScene { |
| t.Fatal(err) |
| } |
| s := &wsScene{ |
| - t: t, hash: string(hashB), app: newCableApp(), raw: &rawBox{arrived: make(chan struct{}, 16)}, |
| + t: t, fx: fx, opts: opts, hash: string(hashB), app: newCableApp(), raw: &rawBox{arrived: make(chan struct{}, 16)}, |
| sink: &memErrSink{}, logs: &lineLog{}, inserted: make(chan *upgradeReservation, 1024), |
| noted: make(map[*upgradeReservation]bool), |
| wrapReturned: make(chan struct{}, 16), loops: make(map[string]*loopHandle), cookies: make(map[string]string), |
| @@ -513,11 +536,9 @@ func newWSScene(t *testing.T, fx tlsFixture) *wsScene { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - pub, err := release.ParsePublicKey(pubB64, "test") |
| - if err != nil { |
| + if s.pub, err = release.ParsePublicKey(pubB64, "test"); err != nil { |
| t.Fatal(err) |
| } |
| - frozen := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC) |
| // The app on a unix socket. |
| sock := filepath.Join(t.TempDir(), "app.sock") |
| @@ -525,7 +546,11 @@ func newWSScene(t *testing.T, fx tlsFixture) *wsScene { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - appSrv := &http.Server{Handler: s.app, ConnContext: func(ctx context.Context, c net.Conn) context.Context { |
| + var app http.Handler = s.app |
| + if opts.app != nil { |
| + app = opts.app(s.app) |
| + } |
| + appSrv := &http.Server{Handler: app, ConnContext: func(ctx context.Context, c net.Conn) context.Context { |
| return context.WithValue(ctx, rawConnKey{}, c) |
| }} |
| go appSrv.Serve(appLn) |
| @@ -534,7 +559,7 @@ func newWSScene(t *testing.T, fx tlsFixture) *wsScene { |
| s.app.closeAll() |
| }) |
| - // The hub. |
| + // The hub's registry. |
| s.hubReg = openReg(t) |
| for _, f := range []string{"home", "away"} { |
| if err := s.hubReg.UpsertFleet(registry.Fleet{Name: f, Account: fwdOwner, Bucket: f + "-data"}); err != nil { |
| @@ -554,6 +579,7 @@ func newWSScene(t *testing.T, fx tlsFixture) *wsScene { |
| wsForward(wsLimitedHost, "home", wsLimitedRate), |
| wsForward(wsRawHost, "home", wsWideRate), |
| wsForward(wsOldHost, "away", wsWideRate), |
| + wsForward(wsLoadHost, "home", wsLoadRate), |
| } { |
| if err := s.hubReg.PutForward(rt); err != nil { |
| t.Fatalf("PutForward(%s): %v", rt.Host, err) |
| @@ -574,25 +600,8 @@ func newWSScene(t *testing.T, fx tlsFixture) *wsScene { |
| if err := s.hubReg.SetGate(wsHubGateHost, s.hash); err != nil { |
| t.Fatal(err) |
| } |
| - s.hub, err = New(s.hubReg, nil) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - t.Cleanup(s.hub.probers.Stop) |
| - s.hub.EnableTunnels(NewTunnelHub("127.0.0.1", map[string]string{"t1": fwdT1Tok})) |
| s.hubStore = &callStore{Store: release.NewDirStore(t.TempDir())} |
| - s.hub.EnableStatic(s.hubStore, pub, filepath.Join(t.TempDir(), "cache")) |
| - s.hub.EnableErrors(s.sink) |
| - s.hub.SetPlanThrottleFor(func(rt registry.Route) (plans.Throttle, bool) { |
| - if rt.Account != fwdOwner || !s.throttle.Load() { |
| - return plans.Throttle{}, false |
| - } |
| - return plans.Throttle{Bandwidth: true, Awake: true, Until: time.Now().Add(time.Hour)}, true |
| - }) |
| - s.hub.open.afterInsert = s.noteInsert |
| - if err := s.hub.Reload(); err != nil { |
| - t.Fatal(err) |
| - } |
| + s.hub = s.newHub(t) |
| // The box. |
| s.boxReg = openReg(t) |
| @@ -602,6 +611,7 @@ func newWSScene(t *testing.T, fx tlsFixture) *wsScene { |
| wsBoxRow(wsHubGateHost, sock, ""), |
| wsBoxRow(wsLimitedHost, sock, wsBoxRate), |
| wsBoxRow(wsOldHost, sock, ""), |
| + wsBoxRow(wsLoadHost, sock, ""), |
| } { |
| if err := s.boxReg.Upsert(rt); err != nil { |
| t.Fatal(err) |
| @@ -618,38 +628,24 @@ func newWSScene(t *testing.T, fx tlsFixture) *wsScene { |
| } |
| t.Cleanup(s.box.probers.Stop) |
| s.boxStore = &callStore{Store: release.NewDirStore(t.TempDir())} |
| - s.box.EnableStatic(s.boxStore, pub, filepath.Join(t.TempDir(), "cache")) |
| + s.box.EnableStatic(s.boxStore, s.pub, filepath.Join(t.TempDir(), "cache")) |
| if err := s.box.Reload(); err != nil { |
| t.Fatal(err) |
| } |
| - for _, e := range []*Edge{s.hub, s.box} { |
| - if e.rateMode != RateEnforce { |
| - t.Fatalf("rate mode %v, want enforce", e.rateMode) |
| - } |
| - e.rateLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000) |
| - e.planLimiter = ratelimit.NewLimiter(func() time.Time { return frozen }, 1000) |
| + if s.box.rateMode != RateEnforce { |
| + t.Fatalf("the box's rate mode %v, want enforce", s.box.rateMode) |
| } |
| + s.box.rateLimiter = ratelimit.NewLimiter(func() time.Time { return wsFrozen }, 1000) |
| + s.box.planLimiter = ratelimit.NewLimiter(func() time.Time { return wsFrozen }, 1000) |
| if got := s.box.current()[wsHost].route.Gate; got != s.hash { |
| t.Fatalf("the box's %s row has gate %q, want the scene's", wsHost, got) |
| } |
| - // The hub's TLS server over the tracking listener, and a second one |
| - // serving the same hub behind case 12's wrapping writers. |
| - s.srv = httptest.NewUnstartedServer(s.hub) |
| - s.ln = &trackingListener{Listener: s.srv.Listener} |
| - s.srv.Listener = s.ln |
| - s.srv.TLS = fx.ServerTLS |
| - s.srv.StartTLS() |
| - s.addr = s.ln.Addr().String() |
| - s.wrapSrv = httptest.NewUnstartedServer(http.HandlerFunc(s.serveWrapped)) |
| - s.wrapSrv.TLS = fx.ServerTLS |
| - s.wrapSrv.StartTLS() |
| - s.wrapAddr = s.wrapSrv.Listener.Addr().String() |
| + // Everything else first, the hub's server last: cleanups run in |
| + // reverse, so the hub's connections close before the loops are |
| + // stopped (a loop whose tunnel is still up returns only when its conn |
| + // dies). |
| t.Cleanup(func() { |
| - // The hub's connections first: a loop whose tunnel is still up |
| - // returns only when its conn dies. |
| - s.ln.closeAll() |
| - s.srv.Close() |
| s.stopLoops() |
| if b := s.wrapBarrier.Load(); b != nil { |
| select { |
| @@ -661,6 +657,14 @@ func newWSScene(t *testing.T, fx tlsFixture) *wsScene { |
| s.wrapSrv.CloseClientConnections() |
| s.wrapSrv.Close() |
| }) |
| + // A second server serving the same hub behind case 12's wrapping |
| + // writers. |
| + s.wrapSrv = httptest.NewUnstartedServer(http.HandlerFunc(s.serveWrapped)) |
| + s.wrapSrv.TLS = fx.ServerTLS |
| + s.wrapSrv.StartTLS() |
| + s.wrapAddr = s.wrapSrv.Listener.Addr().String() |
| + s.serveHub(t, "127.0.0.1:0") |
| + s.addr = s.ln.Addr().String() |
| s.client = &http.Client{ |
| Transport: &http.Transport{ |
| DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { |
| @@ -677,6 +681,65 @@ func newWSScene(t *testing.T, fx tlsFixture) *wsScene { |
| return s |
| } |
| +// wsFrozen is the rate limiters' clock: the scene's buckets never refill. |
| +var wsFrozen = time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC) |
| + |
| +// newHub is one hub process over the scene's hub registry: New, |
| +// EnableTunnels, EnableStatic, EnableErrors, the plan throttle hook, the |
| +// cap in opts and Reload. Task 7's hub restart calls it a second time. |
| +func (s *wsScene) newHub(t *testing.T) *Edge { |
| + t.Helper() |
| + hub, err := New(s.hubReg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(hub.probers.Stop) |
| + hub.EnableTunnels(NewTunnelHub("127.0.0.1", map[string]string{"t1": fwdT1Tok})) |
| + if s.opts.upgradeCap != 0 { |
| + hub.tunnels.upgradeCap = s.opts.upgradeCap |
| + } |
| + hub.EnableStatic(s.hubStore, s.pub, filepath.Join(t.TempDir(), "cache")) |
| + hub.EnableErrors(s.sink) |
| + hub.SetPlanThrottleFor(func(rt registry.Route) (plans.Throttle, bool) { |
| + if rt.Account != fwdOwner || !s.throttle.Load() { |
| + return plans.Throttle{}, false |
| + } |
| + return plans.Throttle{Bandwidth: true, Awake: true, Until: time.Now().Add(time.Hour)}, true |
| + }) |
| + hub.open.afterInsert = func() { s.noteInsert(hub) } |
| + if err := hub.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if hub.rateMode != RateEnforce { |
| + t.Fatalf("the hub's rate mode %v, want enforce", hub.rateMode) |
| + } |
| + hub.rateLimiter = ratelimit.NewLimiter(func() time.Time { return wsFrozen }, 1000) |
| + hub.planLimiter = ratelimit.NewLimiter(func() time.Time { return wsFrozen }, 1000) |
| + return hub |
| +} |
| + |
| +// serveHub serves s.hub over TLS on a new listener at addr, through a |
| +// listener that keeps every accepted connection (s.ln), as s.srv. Its |
| +// cleanup closes every one of them and the server. |
| +func (s *wsScene) serveHub(t *testing.T, addr string) { |
| + t.Helper() |
| + ln, err := net.Listen("tcp", addr) |
| + if err != nil { |
| + t.Fatalf("the hub's listener on %s: %v", addr, err) |
| + } |
| + srv := httptest.NewUnstartedServer(s.hub) |
| + srv.Listener.Close() // httptest's own; the hub serves on ln |
| + tl := &trackingListener{Listener: ln} |
| + srv.Listener = tl |
| + srv.TLS = s.fx.ServerTLS |
| + srv.StartTLS() |
| + s.srv, s.ln = srv, tl |
| + t.Cleanup(func() { |
| + tl.closeAll() |
| + srv.Close() |
| + }) |
| +} |
| + |
| func wsForward(host, fleet, rate string) registry.Route { |
| rt := forwardRow(host, fleet, fwdOwner) |
| rt.RateLimit = rate |
| @@ -699,21 +762,27 @@ type loopHandle struct { |
| done chan struct{} |
| } |
| -// noteInsert is the hub's afterInsert seam: it hands each new reservation |
| -// to the test. |
| -func (s *wsScene) noteInsert() { |
| - o := &s.hub.open |
| - var fresh []*upgradeReservation |
| +// noteInsert is a hub's afterInsert seam: it hands each new reservation to |
| +// the test. |
| +func (s *wsScene) noteInsert(hub *Edge) { |
| + o := &hub.open |
| + var all []*upgradeReservation |
| o.mu.Lock() |
| for _, set := range o.byHost { |
| for r := range set { |
| - if !s.noted[r] { |
| - s.noted[r] = true |
| - fresh = append(fresh, r) |
| - } |
| + all = append(all, r) |
| } |
| } |
| o.mu.Unlock() |
| + var fresh []*upgradeReservation |
| + s.notedMu.Lock() |
| + for _, r := range all { |
| + if !s.noted[r] { |
| + s.noted[r] = true |
| + fresh = append(fresh, r) |
| + } |
| + } |
| + s.notedMu.Unlock() |
| s.inserts.Add(int64(len(fresh))) |
| for _, r := range fresh { |
| select { |
| @@ -768,7 +837,7 @@ func (s *wsScene) startLoop(key, name, token string) { |
| go func() { |
| defer close(done) |
| tunnelclient.Loop(ctx, tunnelclient.Config{ |
| - URL: "https://" + s.addr, Name: name, Token: token, Handler: s.boxHandler(), |
| + URL: "https://" + s.addr, Name: name, Token: token, Handler: s.boxHandler(), Limits: s.opts.limits, |
| Logf: func(format string, args ...any) { |
| line := fmt.Sprintf("box %s: "+format, append([]any{key}, args...)...) |
| s.logs.add(line) |
| @@ -1263,7 +1332,7 @@ func TestTunnelWebSocketEndToEnd(t *testing.T) { |
| if !child { |
| return |
| } |
| - s := newWSScene(t, fx) |
| + s := newWSScene(t, fx, wsOpts{}) |
| // First: the real Loop trusted the fixture over real TLS. |
| waitForTunnelState(t, s.hub.tunnels, wsBox1, "connected", 5*time.Second) |
| @@ -1997,7 +2066,7 @@ func TestTrustedChildIsNeeded(t *testing.T) { |
| if !child { |
| return |
| } |
| - s := newWSScene(t, fx) |
| + s := newWSScene(t, fx, wsOpts{}) |
| deadline := time.Now().Add(5 * time.Second) |
| for time.Now().Before(deadline) { |
| if s.hub.tunnels.State(wsBox1) == "connected" { |
diff --git a/internal/edge/tunnel_ws_load_e2e_test.go b/internal/edge/tunnel_ws_load_e2e_test.go| new file mode 100644 |
| index 000000000..d0ff55f95 |
| --- /dev/null |
| +++ b/internal/edge/tunnel_ws_load_e2e_test.go |
| @@ -0,0 +1,818 @@ |
| +//go:build linux |
| + |
| +package edge |
| + |
| +// Tunnel WebSockets (#471) Task 7, over Task 6's production-wired scene |
| +// (tunnel_ws_e2e_test.go): the maximum load (spec §8.2 case 13), a hub |
| +// restart modelled as process death (case 9), and two Reloads interleaved |
| +// with an open socket (case 18 with real endpoints). |
| +// |
| +// Each test runs the real tunnelclient.Loop over TLS, so each starts in a |
| +// trusted child (trusted_child_test.go). The interleavings are driven by |
| +// Task 4's hooks (reloadScript, reload_serial_test.go) and decided by a |
| +// TryLock and an ordered event log; the only waits are failure bounds. |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/tls" |
| + "encoding/binary" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "os" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/net/websocket" |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/apperr" |
| + "github.com/carlosframework/platform/internal/tunnelclient" |
| +) |
| + |
| +// ---- case 13: maximum load -------------------------------------------------- |
| + |
| +// loadApp serves the load test's paths in front of the cable app: |
| +// |
| +// - /stall: a WebSocket (the cable app's handshake rules) that never |
| +// reads, until the test closes release; then it closes; |
| +// - /hold: a plain GET held until want of them have arrived; |
| +// - /sum: the hex SHA-256 of a plain POST's body. |
| +type loadApp struct { |
| + next http.Handler |
| + stall *websocket.Server |
| + release chan struct{} |
| + releaseOnce sync.Once |
| + |
| + stalls atomic.Int32 // /stall requests that reached the app |
| + mu sync.Mutex |
| + byID map[string]chan *stalledConn |
| + |
| + want int32 |
| + held atomic.Int32 |
| + allHeld chan struct{} |
| +} |
| + |
| +// stalledConn is the app's end of one /stall socket. |
| +type stalledConn struct { |
| + closed chan struct{} |
| + closedAt time.Time // set before closed closes |
| +} |
| + |
| +func newLoadApp(want int) *loadApp { |
| + return &loadApp{release: make(chan struct{}), byID: map[string]chan *stalledConn{}, |
| + want: int32(want), allHeld: make(chan struct{})} |
| +} |
| + |
| +// closeStalls lets every stalled socket close. |
| +func (a *loadApp) closeStalls() { a.releaseOnce.Do(func() { close(a.release) }) } |
| + |
| +// wrap is the scene's opts.app. |
| +func (a *loadApp) wrap(next http.Handler) http.Handler { |
| + a.next = next |
| + a.stall = &websocket.Server{ |
| + Handshake: next.(*cableApp).srv.Handshake, |
| + Handler: func(ws *websocket.Conn) { |
| + c := &stalledConn{closed: make(chan struct{})} |
| + defer func() { |
| + ws.Close() |
| + c.closedAt = time.Now() |
| + close(c.closed) |
| + }() |
| + select { |
| + case a.slot(ws.Request().URL.Query().Get(wsIDParam)) <- c: |
| + default: |
| + } |
| + <-a.release // never reads |
| + }, |
| + } |
| + return a |
| +} |
| + |
| +func (a *loadApp) slot(id string) chan *stalledConn { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + ch := a.byID[id] |
| + if ch == nil { |
| + ch = make(chan *stalledConn, 1) |
| + a.byID[id] = ch |
| + } |
| + return ch |
| +} |
| + |
| +// opened is the app's end of the /stall socket handshake id opened. |
| +func (a *loadApp) opened(t *testing.T, id string) *stalledConn { |
| + t.Helper() |
| + select { |
| + case c := <-a.slot(id): |
| + return c |
| + case <-time.After(5 * time.Second): |
| + t.Fatalf("the app opened no stalled socket for handshake %s within 5 s", id) |
| + return nil |
| + } |
| +} |
| + |
| +func (a *loadApp) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + switch r.URL.Path { |
| + case "/stall": |
| + a.stalls.Add(1) |
| + a.stall.ServeHTTP(w, r) |
| + case "/hold": |
| + if a.held.Add(1) == a.want { |
| + close(a.allHeld) |
| + } |
| + select { |
| + case <-a.allHeld: |
| + io.WriteString(w, "held") |
| + case <-time.After(30 * time.Second): // a failure bound; the test fails first |
| + http.Error(w, "not every GET arrived", http.StatusGatewayTimeout) |
| + } |
| + case "/sum": |
| + h := sha256.New() |
| + if _, err := io.Copy(h, r.Body); err != nil { |
| + http.Error(w, err.Error(), http.StatusBadRequest) |
| + return |
| + } |
| + io.WriteString(w, hex.EncodeToString(h.Sum(nil))) |
| + default: |
| + a.next.ServeHTTP(w, r) |
| + } |
| +} |
| + |
| +// wsChunk is one 32 KiB write: a masked binary WebSocket frame (header 8 |
| +// bytes, zero mask) carrying 32760 bytes, so what the stalled sockets |
| +// carry is well-formed even though no one reads it. |
| +var wsChunk = func() []byte { |
| + const size = 32 << 10 |
| + b := make([]byte, size) |
| + b[0] = 0x82 // FIN, binary |
| + b[1] = 0x80 | 126 |
| + binary.BigEndian.PutUint16(b[2:4], size-8) |
| + // b[4:8] is the zero mask key; the payload is zeros. |
| + return b |
| +}() |
| + |
| +// stallWrite writes wsChunk to c until a write blocks for 500 ms, or |
| +// until ceiling bytes were accepted (a socket flow control never pushed |
| +// back), and returns the bytes the connection accepted and the error that |
| +// stopped it. |
| +func stallWrite(c net.Conn, ceiling int64) (int64, error) { |
| + var n int64 |
| + for n < ceiling { |
| + c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) |
| + m, err := c.Write(wsChunk) |
| + n += int64(m) |
| + if err != nil { |
| + return n, err |
| + } |
| + } |
| + return n, errors.New("never pushed back") |
| +} |
| + |
| +// tcpQueued is what the kernel holds of one client socket's bytes once |
| +// its writes are stalled: the client's unsent send queue (SIOCOUTQ) plus |
| +// the hub's unread receive queue (SIOCINQ) on the connection the hub |
| +// accepted for it, found by address among s.ln's. |
| +func tcpQueued(t *testing.T, s *wsScene, c net.Conn) (out, in int64) { |
| + t.Helper() |
| + ioctl := func(nc net.Conn, req uint) int64 { |
| + tcp, ok := nc.(*net.TCPConn) |
| + if !ok { |
| + t.Fatalf("%T is not a TCP connection", nc) |
| + } |
| + raw, err := tcp.SyscallConn() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var v int |
| + var ierr error |
| + if err := raw.Control(func(fd uintptr) { v, ierr = unix.IoctlGetInt(int(fd), req) }); err != nil || ierr != nil { |
| + t.Fatalf("ioctl %#x: %v %v", req, err, ierr) |
| + } |
| + return int64(v) |
| + } |
| + client := c.(*tls.Conn).NetConn() |
| + out, in = ioctl(client, unix.SIOCOUTQ), -1 |
| + s.ln.mu.Lock() |
| + defer s.ln.mu.Unlock() |
| + for _, ac := range s.ln.conns { |
| + if ac.RemoteAddr().String() == client.LocalAddr().String() { |
| + in = ioctl(ac, unix.SIOCINQ) |
| + } |
| + } |
| + if in < 0 { |
| + t.Fatalf("the hub accepted no connection from %s", client.LocalAddr()) |
| + } |
| + return out, in |
| +} |
| + |
| +// tcpMax is the kernel's ceiling for one TCP buffer (the third field of |
| +// /proc/sys/net/ipv4/tcp_wmem or tcp_rmem): what autotuning may grow a |
| +// socket's send or receive buffer to. |
| +func tcpMax(t *testing.T, name string) int64 { |
| + t.Helper() |
| + b, err := os.ReadFile("/proc/sys/net/ipv4/" + name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f := strings.Fields(string(b)) |
| + if len(f) != 3 { |
| + t.Fatalf("%s: %q", name, b) |
| + } |
| + v, err := strconv.ParseInt(f[2], 10, 64) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return v |
| +} |
| + |
| +// TestTunnelWebSocketMaximumLoad is spec §8.2 case 13: with the cap's |
| +// worth of upgraded sockets open on one tunnel and every app side not |
| +// reading, (a) the plain requests still get stream slots, (b) a plain |
| +// upload still gets connection credit, and (c) each stalled client is |
| +// pushed back by flow control after at most StreamWindow plus 4 MiB of |
| +// kernel buffers. Production values unless -short, scaled under it. |
| +func TestTunnelWebSocketMaximumLoad(t *testing.T) { |
| + child, fx := runTrustedChild(t) |
| + if !child { |
| + return |
| + } |
| + lim, capN, gets, postLen := tunnelclient.DefaultLimits, tunnelUpgradeCap, 100, 16<<20 |
| + opts := wsOpts{} |
| + if testing.Short() { |
| + lim, capN, gets, postLen = tunnelclient.Limits{MaxStreams: 16, StreamWindow: 64 << 10, ConnWindow: 768 << 10}, 8, 7, 512<<10 |
| + opts.limits, opts.upgradeCap = &lim, capN |
| + } else if capN != 128 || lim != (tunnelclient.Limits{MaxStreams: 250, StreamWindow: 1 << 20, ConnWindow: 160 << 20}) { |
| + t.Fatalf("the production values moved: cap %d, limits %+v", capN, lim) |
| + } |
| + // The shape the guarantee needs, at whichever scale: the cap below the |
| + // stream count with room for the GETs, and connection credit beyond the |
| + // stalled sockets' windows for the POST. |
| + if capN+gets >= int(lim.MaxStreams) || int64(lim.ConnWindow) <= int64(capN)*int64(lim.StreamWindow) { |
| + t.Fatalf("the scale is wrong: cap %d + %d GETs vs %d streams; conn window %d vs %d x %d", |
| + capN, gets, lim.MaxStreams, lim.ConnWindow, capN, lim.StreamWindow) |
| + } |
| + la := newLoadApp(gets) |
| + opts.app = la.wrap |
| + s := newWSScene(t, fx, opts) |
| + t.Cleanup(la.closeStalls) // on a failure; first of the cleanups |
| + waitForTunnelState(t, s.hub.tunnels, wsBox1, "connected", 5*time.Second) |
| + tc := s.channel(t, wsBox1) |
| + if s.hub.tunnels.upgradeCap != capN { |
| + t.Fatalf("the hub's cap is %d, want %d", s.hub.tunnels.upgradeCap, capN) |
| + } |
| + t.Logf("scale: cap %d, limits %+v, %d GETs, a %d-byte POST", capN, lim, gets, postLen) |
| + |
| + // The cap's worth of sockets, each matched to its app end by its id. |
| + type stalled struct { |
| + h hs |
| + ac *stalledConn |
| + } |
| + socks := make([]stalled, capN) |
| + for i := range socks { |
| + id := newHandshakeID() |
| + h := s.sendHandshake(t, s.addr, wsLoadHost, "/stall?"+wsIDParam+"="+id, "", "websocket") |
| + h.read(t) |
| + wantStatus(t, h, http.StatusSwitchingProtocols, fmt.Sprintf("upgrade %d", i+1)) |
| + if got, want := h.resp.Header.Get("Sec-WebSocket-Accept"), acceptFor(h.key); got != want { |
| + t.Fatalf("upgrade %d: Sec-WebSocket-Accept %q, want the app's %q", i+1, got, want) |
| + } |
| + if h.br.Buffered() != 0 { |
| + t.Fatalf("upgrade %d: the app sent %d bytes after its 101", i+1, h.br.Buffered()) |
| + } |
| + socks[i] = stalled{h: h, ac: la.opened(t, id)} |
| + } |
| + if n, _ := openCount(s.hub, tc); n != capN { |
| + t.Fatalf("with %d sockets open the channel's count is %d", capN, n) |
| + } |
| + |
| + // (c) Every client writes until flow control pushes it back. The |
| + // spec's bound is StreamWindow plus 4 MiB of kernel buffers. On Linux |
| + // the kernel's share is not 4 MiB: autotuning grows the client's send |
| + // buffer to tcp_wmem's ceiling and the hub's receive buffer toward |
| + // tcp_rmem's (4 MiB and 6 MiB by default, measured at nearly 10 MiB |
| + // between them on loopback). So the kernel's queues on the client's |
| + // connection are measured once the writes stall and taken off, and |
| + // what is left, everything the processes and the box's side hold, is |
| + // held to StreamWindow + 4 MiB. (The queues are the kernel's to bound, |
| + // near its ceilings: a send queue can pass tcp_wmem by part of a |
| + // segment.) |
| + wmax, rmax := tcpMax(t, "tcp_wmem"), tcpMax(t, "tcp_rmem") |
| + bound := int64(lim.StreamWindow) + 4<<20 |
| + type pushed struct { |
| + n, out, in int64 |
| + err error |
| + } |
| + res := make([]pushed, capN) |
| + for _, sk := range socks { |
| + // On a failure: drop each connection, as the success path does, |
| + // rather than let a TLS close wait behind the stalled bytes. |
| + t.Cleanup(func() { sk.h.conn.(*tls.Conn).NetConn().Close() }) |
| + } |
| + writing := time.Now() |
| + var wg sync.WaitGroup |
| + for i := range socks { |
| + wg.Go(func() { |
| + n, err := stallWrite(socks[i].h.conn, bound+wmax+rmax+(4<<20)) |
| + res[i] = pushed{n: n, err: err} |
| + }) |
| + } |
| + wg.Wait() |
| + took := time.Since(writing) |
| + var lo, hi, maxOut, maxIn, total int64 = 1 << 62, 0, 0, 0, 0 |
| + for i := range res { |
| + r := &res[i] |
| + var ne net.Error |
| + if !errors.As(r.err, &ne) || !ne.Timeout() { |
| + t.Fatalf("socket %d: its writes stopped with %v after %d bytes, want a write deadline", i+1, r.err, r.n) |
| + } |
| + r.out, r.in = tcpQueued(t, s, socks[i].h.conn) |
| + if rest := r.n - r.out - r.in; rest > bound { |
| + t.Fatalf("socket %d: %d bytes accepted, %d of them beyond the TCP queues (%d + %d); want at most StreamWindow + 4 MiB = %d", |
| + i+1, r.n, rest, r.out, r.in, bound) |
| + } |
| + rest := r.n - r.out - r.in |
| + lo, hi, total = min(lo, rest), max(hi, rest), total+r.n |
| + maxOut, maxIn = max(maxOut, r.out), max(maxIn, r.in) |
| + } |
| + t.Logf("each of %d sockets pushed back with %d to %d bytes beyond the TCP queues (bound %d), in %s; the queues at most %d (client; tcp_wmem %d) and %d (hub; tcp_rmem %d); %d bytes accepted in all", |
| + capN, lo, hi, bound, took.Round(time.Millisecond), maxOut, wmax, maxIn, rmax, total) |
| + for i, sk := range socks { |
| + notClosed(t, sk.ac.closed, fmt.Sprintf("the app's end of socket %d", i+1)) |
| + } |
| + |
| + // The next handshake is refused at the cap, and reaches no app. |
| + stalls := la.stalls.Load() |
| + h := s.handshake(t, wsLoadHost, "/stall?"+wsIDParam+"="+newHandshakeID(), "") |
| + wantStatus(t, h, http.StatusServiceUnavailable, fmt.Sprintf("upgrade %d", capN+1)) |
| + if got := h.resp.Header.Get("Retry-After"); got != "5" || h.body != tunnelBusyBody+"\n" { |
| + t.Fatalf("upgrade %d: Retry-After %q body %q, want 5 and TWS-C03", capN+1, got, h.body) |
| + } |
| + wantCause(t, s.sink, http.StatusServiceUnavailable, apperr.CauseTunnelBusy) |
| + if got := la.stalls.Load(); got != stalls { |
| + t.Fatalf("the refused upgrade reached the app") |
| + } |
| + |
| + // (a) While all stay stalled: the GETs, held by the app until every |
| + // one has arrived, all arrive and then complete. |
| + type answer struct { |
| + status int |
| + body string |
| + err error |
| + } |
| + answers := make(chan answer, gets) |
| + for i := range gets { |
| + go func() { |
| + resp, err := s.client.Get(fmt.Sprintf("https://%s/hold?i=%d", wsLoadHost, i)) |
| + if err != nil { |
| + answers <- answer{err: err} |
| + return |
| + } |
| + b, err := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + answers <- answer{resp.StatusCode, string(b), err} |
| + }() |
| + } |
| + select { |
| + case <-la.allHeld: |
| + case <-time.After(10 * time.Second): |
| + t.Fatalf("%d of %d concurrent GETs reached the app within 10 s with %d sockets stalled", la.held.Load(), gets, capN) |
| + } |
| + for range gets { |
| + select { |
| + case a := <-answers: |
| + if a.err != nil || a.status != http.StatusOK || a.body != "held" { |
| + t.Fatalf("a held GET: %d %q %v, want 200 held", a.status, a.body, a.err) |
| + } |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("a held GET did not complete within 10 s of all arriving") |
| + } |
| + } |
| + |
| + // (b) A plain upload completes, intact, within 10 s. |
| + body := make([]byte, postLen) |
| + rand.Read(body) |
| + want := sha256.Sum256(body) |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://"+wsLoadHost+"/sum", bytes.NewReader(body)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + start := time.Now() |
| + resp, err := s.client.Do(req) |
| + if err != nil { |
| + t.Fatalf("the %d-byte POST with %d sockets stalled: %v after %s", postLen, capN, err, time.Since(start).Round(time.Millisecond)) |
| + } |
| + got, err := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if err != nil || resp.StatusCode != http.StatusOK || string(got) != hex.EncodeToString(want[:]) { |
| + t.Fatalf("the POST: %d %q %v, want 200 and %x", resp.StatusCode, got, err, want) |
| + } |
| + t.Logf("the %d-byte POST completed in %s", postLen, time.Since(start).Round(time.Millisecond)) |
| + for i, sk := range socks { |
| + notClosed(t, sk.ac.closed, fmt.Sprintf("the app's end of socket %d after the plain traffic", i+1)) |
| + } |
| + if n, _ := openCount(s.hub, tc); n != capN { |
| + t.Fatalf("after the plain traffic the channel's count is %d, want %d", n, capN) |
| + } |
| + |
| + // Close every socket at both ends: the count returns to 0. |
| + // The clients drop their connections (a TLS close would first wait to |
| + // send its alert behind the stalled bytes), and the apps close theirs. |
| + deadline := time.Now().Add(10 * time.Second) |
| + for _, sk := range socks { |
| + sk.h.conn.(*tls.Conn).NetConn().Close() |
| + } |
| + la.closeStalls() |
| + for { |
| + n, ok := openCount(s.hub, tc) |
| + if n == 0 && !ok { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("10 s after every socket closed the channel's count is %d", n) |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + if held := heldFor(s.hub, wsLoadHost); held != 0 { |
| + t.Fatalf("the registry still holds %d reservations for %s", held, wsLoadHost) |
| + } |
| + |
| + // A new upgrade on the same channel. |
| + c, _ := s.openCable(t, wsLoadHost, "") |
| + if f := c.next(t); f != `{"type":"welcome"}` { |
| + t.Fatalf("first frame %q, want the welcome", f) |
| + } |
| + c.subscribe(t) |
| + c.echo(t, "after the load") |
| + if s.channel(t, wsBox1) != tc { |
| + t.Fatal("the channel was replaced during the load") |
| + } |
| + c.ws.Close() |
| + waitOpen(t, s.hub, tc, 0, "after the new upgrade closed") |
| +} |
| + |
| +// ---- case 9: hub restart ------------------------------------------------------ |
| + |
| +// TestTunnelWebSocketHubRestart is spec §8.2 case 9 (R1-3). Closing the |
| +// test server is not a restart: neither Server.Close nor Shutdown touches a |
| +// hijacked connection, and the tunnel and the public socket are both |
| +// hijacked. The hub dies as a process does: its listener and every |
| +// connection it accepted close, hijacked ones included. |
| +func TestTunnelWebSocketHubRestart(t *testing.T) { |
| + child, fx := runTrustedChild(t) |
| + if !child { |
| + return |
| + } |
| + |
| + t.Run("processDeath", func(t *testing.T) { |
| + s := newWSScene(t, fx, wsOpts{}) |
| + waitForTunnelState(t, s.hub.tunnels, wsBox1, "connected", 5*time.Second) |
| + oldHub, oldTC, oldSrv := s.hub, s.channel(t, wsBox1), s.srv |
| + c, ac := s.openShop(t) |
| + c.echo(t, "before the hub dies") |
| + |
| + // The hub dies. |
| + deadline := time.Now().Add(2 * time.Second) |
| + s.ln.closeAll() |
| + closedBy(t, deadline, "the hub died", c, ac) |
| + for !s.logs.contains("box " + wsBox1 + ": tunnel lost") { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("the box's loop did not see its tunnel close within 2 s") |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + oldSrv.Close() |
| + waitOpen(t, oldHub, oldTC, 0, "the dead hub's registry") |
| + |
| + // A new hub process, over the same registry, on the same address. |
| + s.hub = s.newHub(t) |
| + if s.hub.tunnels.channel(wsBox1) != nil { |
| + t.Fatal("the new hub has a channel before it listens") |
| + } |
| + s.serveHub(t, s.addr) |
| + listening := time.Now() |
| + tc := s.waitChannel(t, wsBox1, nil, tunnelclient.BackoffCap+tunnelclient.BackoffCap/2) |
| + t.Logf("%s re-registered %s after the new hub listened", wsBox1, time.Since(listening).Round(time.Millisecond)) |
| + if tc.caps != tunnelclient.CapUpgrade { |
| + t.Fatalf("%s re-registered with caps %q, want %s", wsBox1, tc.caps, tunnelclient.CapUpgrade) |
| + } |
| + |
| + // A new handshake through the new hub. |
| + c2, ac2 := s.openShop(t) |
| + c2.echo(t, "through the new hub") |
| + notClosed(t, ac2.closed, "the new socket's app end") |
| + c2.ws.Close() |
| + waitOpen(t, s.hub, tc, 0, "after the new socket closed") |
| + }) |
| + |
| + // Shutdown alone closes the listener and idle connections, and leaves |
| + // the hijacked ones, as edge.go's shutdown does: the open socket and |
| + // the tunnel under it carry on. |
| + t.Run("listenerShutdownOnly", func(t *testing.T) { |
| + s := newWSScene(t, fx, wsOpts{}) |
| + waitForTunnelState(t, s.hub.tunnels, wsBox1, "connected", 5*time.Second) |
| + tc := s.channel(t, wsBox1) |
| + c, ac := s.openShop(t) |
| + c.echo(t, "before the shutdown") |
| + |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + if err := s.srv.Config.Shutdown(ctx); err != nil { |
| + t.Fatalf("Shutdown: %v", err) |
| + } |
| + // Control: the shutdown happened; the listener is gone. |
| + if conn, err := net.DialTimeout("tcp", s.addr, time.Second); err == nil { |
| + conn.Close() |
| + t.Fatal("the hub still accepts connections after Shutdown") |
| + } |
| + for i := range 20 { |
| + c.echo(t, fmt.Sprintf("after the shutdown, %d", i)) |
| + } |
| + notClosed(t, c.closed, "the client's socket after the shutdown") |
| + notClosed(t, ac.closed, "the app's socket after the shutdown") |
| + if s.hub.tunnels.channel(wsBox1) != tc { |
| + t.Fatal("the tunnel was replaced across the shutdown") |
| + } |
| + if n, _ := openCount(s.hub, tc); n != 1 { |
| + t.Fatalf("after the shutdown the channel's count is %d, want 1", n) |
| + } |
| + deadline := time.Now().Add(2 * time.Second) |
| + c.ws.Close() |
| + closedBy(t, deadline, "the client closed after the shutdown", nil, ac) |
| + waitOpen(t, s.hub, tc, 0, "after the socket closed") |
| + }) |
| +} |
| + |
| +// ---- case 18: two Reloads, with sockets ------------------------------------ |
| + |
| +// wsReloadSocket opens the shop's socket and returns it with its |
| +// reservation, matched by the afterInsert seam. |
| +func wsReloadSocket(t *testing.T, s *wsScene) (*cableClient, *appConn, *upgradeReservation) { |
| + t.Helper() |
| + s.drainInserted() |
| + c, ac := s.openShop(t) |
| + r := s.nextInserted(t) |
| + if r.host != wsHost || r.ten.Arm != ArmForward { |
| + t.Fatalf("the socket's reservation is for %s under %+v, want %s on the forward arm", r.host, r.ten, wsHost) |
| + } |
| + c.echo(t, "before the reloads") |
| + return c, ac, r |
| +} |
| + |
| +// registered reports whether r is in the hub's registry. |
| +func registered(e *Edge, r *upgradeReservation) bool { |
| + e.open.mu.Lock() |
| + defer e.open.mu.Unlock() |
| + _, in := e.open.byHost[r.host][r] |
| + return in |
| +} |
| + |
| +// stillOpen asserts the socket is open, carries an echo and its |
| +// reservation is registered and unreleased. |
| +func stillOpen(t *testing.T, s *wsScene, c *cableClient, ac *appConn, r *upgradeReservation, when string) { |
| + t.Helper() |
| + if !registered(s.hub, r) || r.firstReleaser() != relNone { |
| + t.Fatalf("%s: the reservation is registered %v, released by %v; want open", when, registered(s.hub, r), r.firstReleaser()) |
| + } |
| + notClosed(t, c.closed, when+": the client's socket") |
| + notClosed(t, ac.closed, when+": the app's socket") |
| + c.echo(t, when) |
| +} |
| + |
| +// refusedNow asserts a new handshake for the shop is not a 101 and reaches |
| +// no app. |
| +func refusedNow(t *testing.T, s *wsScene, when string) { |
| + t.Helper() |
| + before := len(s.app.seenFor(wsHost)) |
| + h := s.handshake(t, wsHost, "/cable", s.cookie(t, wsHost)) |
| + if h.resp.StatusCode == http.StatusSwitchingProtocols { |
| + t.Fatalf("%s: a new handshake got a 101", when) |
| + } |
| + if n := len(s.app.seenFor(wsHost)); n != before { |
| + t.Fatalf("%s: the app saw %d requests, want none", when, n-before) |
| + } |
| + t.Logf("%s: the new handshake got %d", when, h.resp.StatusCode) |
| +} |
| + |
| +// TestTunnelWebSocketTwoReloads is spec §8.2 case 18 over the real scene: |
| +// Task 4's schedule (TestTwoReloadsInterleave) with a socket open on the |
| +// forward row, and its item 7, the close at both endpoints. |
| +func TestTunnelWebSocketTwoReloads(t *testing.T) { |
| + child, fx := runTrustedChild(t) |
| + if !child { |
| + return |
| + } |
| + scene := func(t *testing.T) *wsScene { |
| + s := newWSScene(t, fx, wsOpts{}) |
| + waitForTunnelState(t, s.hub.tunnels, wsBox1, "connected", 5*time.Second) |
| + return s |
| + } |
| + |
| + // Items 1 to 7. |
| + t.Run("in order", func(t *testing.T) { |
| + s := scene(t) |
| + tc := s.channel(t, wsBox1) |
| + c, ac, res := wsReloadSocket(t, s) |
| + sc := newReloadScript(t, s.hub, "A", "B") |
| + sc.hold("A:afterRead", "A:beforePublish", "A:afterPublish", "A:afterSweep", "B:afterPublish", "B:afterSweep") |
| + tick := startTickedWatch(t, s.hub, sc) |
| + |
| + // 1. A (SIGHUP's stand-in) stops after its registry reads. |
| + aDone := goReload(s.hub) |
| + sc.wait("A:afterRead") |
| + // 2. The owner changes, read back. |
| + before := fingerprint(t, s.hub) |
| + setFleetOwner(t, s.hub, "home", fwdOther) |
| + fp := fingerprint(t, s.hub) |
| + if fp == before { |
| + t.Fatal("the owner change did not move the fingerprint") |
| + } |
| + // 3. Contention, decided before anything that depends on scheduling. |
| + heldByAnother(t, s.hub, "A") |
| + // 4. Watch reads the new fingerprint and calls B, which waits. |
| + sendTick(t, tick) |
| + sc.wait("B:enter") |
| + heldByAnother(t, s.hub, "A") |
| + if sc.has("B:afterRead") { |
| + t.Fatalf("B read the registry while A holds the reload: %v", sc.snapshot()) |
| + } |
| + // 5. A's barriers, one at a time. |
| + sc.release("A:afterRead") |
| + sc.wait("A:beforePublish") |
| + sc.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish") |
| + sc.release("A:beforePublish") |
| + sc.wait("A:afterPublish") |
| + sc.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish") |
| + if ten, ok := tenancyAt(s.hub, wsHost); !ok || ten != res.ten { |
| + t.Fatalf("after A's swap: %s tenancy %+v (served %v), want A's map, %+v", wsHost, ten, ok, res.ten) |
| + } |
| + sc.release("A:afterPublish") |
| + sc.wait("A:afterSweep") |
| + sc.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish", "A:afterSweep") |
| + stillOpen(t, s, c, ac, res, "after A's sweep") |
| + heldByAnother(t, s.hub, "A") |
| + sc.release("A:afterSweep") |
| + awaitReload(t, aDone, "A") |
| + |
| + // 6. B reads the new registry, publishes and sweeps. |
| + sc.wait("B:afterPublish") |
| + if _, ok := tenancyAt(s.hub, wsHost); ok { |
| + t.Fatalf("after B's swap: %s is still served", wsHost) |
| + } |
| + stillOpen(t, s, c, ac, res, "after B's swap, before its sweep") |
| + // 7. One deadline, taken at the trigger: B's sweep runs when its |
| + // afterPublish barrier opens. |
| + deadline := time.Now().Add(2 * time.Second) |
| + sc.release("B:afterPublish") |
| + sc.wait("B:afterSweep") |
| + if sc.has("record:before") { |
| + t.Fatalf("Watch recorded before B returned: %v", sc.snapshot()) |
| + } |
| + if registered(s.hub, res) { |
| + t.Fatal("after B's sweep the reservation is still registered") |
| + } |
| + closedBy(t, deadline, "B's sweep", c, ac) |
| + if got := res.firstReleaser(); got != relSweep { |
| + t.Fatalf("the first releaser is %v, want relSweep", got) |
| + } |
| + sc.release("B:afterSweep") |
| + sc.wait("record:after") |
| + sc.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish", "A:afterSweep", |
| + "B:afterRead", "B:beforePublish", "B:afterPublish", "B:afterSweep", "record:before", "record:after") |
| + if got := sc.recorded(); !slices.Equal(got, []string{fp}) { |
| + t.Fatalf("Watch recorded %q, want the fingerprint read after the owner change, %q", got, fp) |
| + } |
| + waitOpen(t, s.hub, tc, 0, "after B's sweep") |
| + refusedNow(t, s, "after B") |
| + }) |
| + |
| + // Item 8: B's registry read fails. Nothing of B is published or |
| + // recorded, the socket stays; the next tick's C swaps, sweeps and closes |
| + // it, and only then records. |
| + t.Run("B fails", func(t *testing.T) { |
| + s := scene(t) |
| + tc := s.channel(t, wsBox1) |
| + c, ac, res := wsReloadSocket(t, s) |
| + sc := newReloadScript(t, s.hub, "A", "B", "C") |
| + sc.hold("A:afterRead", "C:enter") |
| + sc.failAt("B:afterRead", errors.New("registry read failed (test)")) |
| + tick := startTickedWatch(t, s.hub, sc) |
| + |
| + aDone := goReload(s.hub) |
| + sc.wait("A:afterRead") |
| + setFleetOwner(t, s.hub, "home", fwdOther) |
| + fp := fingerprint(t, s.hub) |
| + heldByAnother(t, s.hub, "A") |
| + sendTick(t, tick) |
| + sc.wait("B:enter") |
| + heldByAnother(t, s.hub, "A") |
| + sc.release("A:afterRead") |
| + awaitReload(t, aDone, "A") |
| + sc.wait("B:afterRead") |
| + // Watch takes this tick only after B returned its error. |
| + sendTick(t, tick) |
| + sc.wait("C:enter") |
| + sc.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish", "A:afterSweep", |
| + "B:afterRead", "C:enter") |
| + if got := sc.recorded(); len(got) != 0 { |
| + t.Fatalf("Watch recorded %q after B failed", got) |
| + } |
| + if ten, ok := tenancyAt(s.hub, wsHost); !ok || ten != res.ten { |
| + t.Fatalf("after B failed: %s tenancy %+v (served %v), want A's map still current", wsHost, ten, ok) |
| + } |
| + stillOpen(t, s, c, ac, res, "after B failed") |
| + deadline := time.Now().Add(2 * time.Second) |
| + sc.release("C:enter") |
| + sc.wait("record:after") |
| + sc.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish", "A:afterSweep", |
| + "B:afterRead", "C:enter", "C:afterRead", "C:beforePublish", "C:afterPublish", "C:afterSweep", |
| + "record:before", "record:after") |
| + closedBy(t, deadline, "C's sweep", c, ac) |
| + if got := res.firstReleaser(); got != relSweep { |
| + t.Fatalf("the first releaser is %v, want relSweep", got) |
| + } |
| + if got := sc.recorded(); !slices.Equal(got, []string{fp}) { |
| + t.Fatalf("Watch recorded %q, want %q", got, fp) |
| + } |
| + waitOpen(t, s.hub, tc, 0, "after C's sweep") |
| + refusedNow(t, s, "after C") |
| + }) |
| + |
| + // Item 9: the revoking B runs to its sweep first, closing the socket; |
| + // A, started after the owner change, reads only after B returned, and |
| + // the host stays refused. |
| + t.Run("reversed", func(t *testing.T) { |
| + s := scene(t) |
| + tc := s.channel(t, wsBox1) |
| + c, ac, res := wsReloadSocket(t, s) |
| + sc := newReloadScript(t, s.hub, "B", "A") |
| + sc.hold("B:afterSweep") |
| + tick := startTickedWatch(t, s.hub, sc) |
| + |
| + setFleetOwner(t, s.hub, "home", fwdOther) |
| + fp := fingerprint(t, s.hub) |
| + deadline := time.Now().Add(2 * time.Second) |
| + sendTick(t, tick) |
| + sc.wait("B:afterSweep") |
| + if registered(s.hub, res) { |
| + t.Fatal("after B's sweep the reservation is still registered") |
| + } |
| + closedBy(t, deadline, "B's sweep", c, ac) |
| + if got := res.firstReleaser(); got != relSweep { |
| + t.Fatalf("the first releaser is %v, want relSweep", got) |
| + } |
| + aDone := goReload(s.hub) |
| + sc.wait("A:enter") |
| + heldByAnother(t, s.hub, "B") |
| + if sc.has("A:afterRead") { |
| + t.Fatalf("A read the registry while B holds the reload: %v", sc.snapshot()) |
| + } |
| + sc.release("B:afterSweep") |
| + awaitReload(t, aDone, "A") |
| + sc.wait("record:after") |
| + |
| + // B's run and Watch's record are one ordered sequence, and so is |
| + // A's; A entered after B's sweep and read only after B returned. |
| + // (Watch's record and A's run race once B has returned, so their |
| + // relative order is not asserted.) |
| + log := sc.snapshot() |
| + var bw, a []string |
| + for _, ev := range log { |
| + if ev[0] == 'A' { |
| + a = append(a, ev) |
| + } else { |
| + bw = append(bw, ev) |
| + } |
| + } |
| + if want := []string{"B:enter", "B:afterRead", "B:beforePublish", "B:afterPublish", "B:afterSweep", "record:before", "record:after"}; !slices.Equal(bw, want) { |
| + t.Fatalf("B and Watch: %v, want %v (log %v)", bw, want, log) |
| + } |
| + if want := []string{"A:enter", "A:afterRead", "A:beforePublish", "A:afterPublish", "A:afterSweep"}; !slices.Equal(a, want) { |
| + t.Fatalf("A: %v, want %v (log %v)", a, want, log) |
| + } |
| + if slices.Index(log, "A:enter") < slices.Index(log, "B:afterSweep") { |
| + t.Fatalf("A entered before B's sweep: %v", log) |
| + } |
| + if _, ok := tenancyAt(s.hub, wsHost); ok { |
| + t.Fatalf("after A: %s is served again", wsHost) |
| + } |
| + if got := sc.recorded(); !slices.Equal(got, []string{fp}) { |
| + t.Fatalf("Watch recorded %q, want %q", got, fp) |
| + } |
| + waitOpen(t, s.hub, tc, 0, "after B's sweep") |
| + refusedNow(t, s, "after A") |
| + }) |
| +} |