diff --git a/handler.go b/handler.go index 3517a28..af3abde 100644 --- a/handler.go +++ b/handler.go @@ -648,7 +648,11 @@ func pollStreamResumable(w http.ResponseWriter, r *http.Request, s *Session, cfg if !s.att.isCurrent(att) { return } + // The current attachment was nudged, not failed. Keep the + // handled signal from being mistaken for an I/O error if this + // loop gains a shared error check in the future. interrupted = true + err = nil } if ack, due := s.rs.takeAck(); due { diff --git a/reliable.go b/reliable.go index 8954cb2..820a5a5 100644 --- a/reliable.go +++ b/reliable.go @@ -222,6 +222,23 @@ func (r *reliable) recvOffsetNow() uint64 { return r.recvOffset } +type reliableProgress struct { + acked uint64 + recv uint64 +} + +// progress snapshots bytes the peer has confirmed receiving from us and bytes +// we have received from it. sendOffset is deliberately excluded: nextOut +// advances it before the transport write, so it proves only that local input +// was consumed, not that a failing leg moved anything across the network. +// ackedOffset includes both in-band acks and the peer's recv offset accepted by +// resumeOut, making both fields evidence of peer-visible progress. +func (r *reliable) progress() reliableProgress { + r.mu.Lock() + defer r.mu.Unlock() + return reliableProgress{acked: r.ackedOffset, recv: r.recvOffset} +} + // unacked is how many sent bytes the peer has not acknowledged — the replay // buffer's current size. func (r *reliable) unacked() int { diff --git a/reliable_test.go b/reliable_test.go index a47c632..b5de47f 100644 --- a/reliable_test.go +++ b/reliable_test.go @@ -90,6 +90,50 @@ func TestReliableNumbersRetainsAndReplays(t *testing.T) { } } +func TestReliableProgressOnlyCountsPeerVisibleBytes(t *testing.T) { + r := newTestReliable(1 << 20) + initial := r.progress() + + // Pulling local input assigns offsets before the caller attempts its + // transport write. It must not count as progress: that write may fail + // without a single byte reaching the peer. + r.out.Write([]byte("abc")) + mustNext(t, r, 64) + if got := r.progress(); got != initial { + t.Fatalf("progress changed after nextOut only: got %+v, want %+v", got, initial) + } + + if err := r.ack(3); err != nil { + t.Fatal(err) + } + afterAck := r.progress() + if afterAck == initial || afterAck.acked != 3 { + t.Fatalf("progress after peer ack = %+v, want acked=3", afterAck) + } + + // A resume handshake's peer recv offset is equally authoritative even + // when the in-band ack was lost with the old transport. + r.out.Write([]byte("def")) + mustNext(t, r, 64) + beforeResume := r.progress() + if !r.resumeOut(6) { + t.Fatal("resumeOut refused the peer's received offset") + } + afterResume := r.progress() + if afterResume == beforeResume || afterResume.acked != 6 { + t.Fatalf("progress after resume offset = %+v, want acked=6", afterResume) + } + + beforeRecv := r.progress() + if err := r.recvIn(0, []byte("down")); err != nil { + t.Fatal(err) + } + afterRecv := r.progress() + if afterRecv == beforeRecv || afterRecv.recv != 4 { + t.Fatalf("progress after received bytes = %+v, want recv=4", afterRecv) + } +} + func TestReliableRecvDedupsReplayAndRefusesGaps(t *testing.T) { r := newTestReliable(1 << 20) diff --git a/resumable_client.go b/resumable_client.go index 6ff92fe..59d24e8 100644 --- a/resumable_client.go +++ b/resumable_client.go @@ -184,6 +184,34 @@ func (c *resumableConn) onSessionClosed() { c.fail() } +const ( + // resumableLegsMinStable is long enough to distinguish a transport that + // never became usable after resume from an ordinary established leg that + // later failed. A stable leg resets the consecutive-fast-failure guard. + resumableLegsMinStable = 2 * time.Second + // maxConsecutiveFastResumes bounds the otherwise unthrottled case where + // every resume handshake succeeds but its replacement legs fail at once. + maxConsecutiveFastResumes = 5 +) + +type resumeStabilityGuard struct { + consecutiveFast int +} + +// record reports whether the session should be abandoned after a successful +// resume. A leg that moved bytes is useful even if it was short-lived (for +// example, tests and real flaky links can fail repeatedly during a bulk +// transfer), so either duration or progress resets the guard. The inputs make +// its boundary and reset behaviour testable without sleeping. +func (g *resumeStabilityGuard) record(legsDuration time.Duration, progressed bool) bool { + if legsDuration >= resumableLegsMinStable || progressed { + g.consecutiveFast = 0 + return false + } + g.consecutiveFast++ + return g.consecutiveFast >= maxConsecutiveFastResumes +} + // supervise runs one set of legs after another until the connection is // closed or the session cannot be kept. Between sets it decides, from why // the previous set ended, whether resuming is even worth attempting: a @@ -194,8 +222,12 @@ func (c *resumableConn) onSessionClosed() { // what resume is for. func (c *resumableConn) supervise() { defer c.wg.Done() + var stability resumeStabilityGuard for { + legsStart := time.Now() + progressBefore := c.rl.progress() err := c.runLegs() + legsDuration := time.Since(legsStart) if c.ctx.Err() != nil || c.closed.Load() { return } @@ -222,6 +254,18 @@ func (c *resumableConn) supervise() { c.fail() return } + // Include peer progress learned by resumeOut from the handshake, not + // merely in-band acks observed before runLegs returned. + progressed := c.rl.progress() != progressBefore + if stability.record(legsDuration, progressed) { + c.logger.Warn("pollmux: replacement legs failed too quickly after consecutive resumes, abandoning session", + "consecutive_fast_resumes", stability.consecutiveFast, + "last_legs_duration", legsDuration, + "error", err, + ) + c.fail() + return + } c.logger.Info("pollmux: session resumed", "recv_offset", c.rl.recvOffsetNow(), "unacked_bytes", c.rl.unacked()) } @@ -530,7 +574,10 @@ func (c *resumableConn) feedSendStream(ctx context.Context, pw *io.PipeWriter) e pw.CloseWithError(ctx.Err()) return ctx.Err() } + // This is a wake-up signal, not a transport error. Clear it so + // later code cannot accidentally propagate it as a leg failure. interrupted = true + err = nil } if ack, due := c.rl.takeAck(); due { @@ -638,7 +685,11 @@ func (c *resumableConn) wsWriteLoop(ctx context.Context, ws *websocket.Conn) err if ctx.Err() != nil { return ctx.Err() } + // The interrupt only asks this leg to re-check cancellation and + // send a pending ack. Leaving it in err makes the final err check + // below tear down a healthy WebSocket when no ack is due. interrupted = true + err = nil } wctx, cancel := context.WithTimeout(ctx, c.idleTimeout) diff --git a/resume_test.go b/resume_test.go index 5aa287c..93ab21e 100644 --- a/resume_test.go +++ b/resume_test.go @@ -562,6 +562,92 @@ func TestResumeAfterDeleteFailsAndHookFiresOnce(t *testing.T) { } } +// --------------------------------------------------------------------------- +// client supervisor safety guard +// --------------------------------------------------------------------------- + +func TestResumeStabilityGuardAbandonsConsecutiveFastLegs(t *testing.T) { + var g resumeStabilityGuard + for i := 1; i < maxConsecutiveFastResumes; i++ { + if g.record(resumableLegsMinStable-time.Nanosecond, false) { + t.Fatalf("guard abandoned after %d fast resumes, want %d", i, maxConsecutiveFastResumes) + } + } + if !g.record(resumableLegsMinStable-time.Nanosecond, false) { + t.Fatalf("guard did not abandon after %d consecutive fast resumes", maxConsecutiveFastResumes) + } +} + +func TestResumeStabilityGuardStableOrProductiveLegResetsCounter(t *testing.T) { + var g resumeStabilityGuard + for i := 0; i < maxConsecutiveFastResumes-1; i++ { + if g.record(time.Millisecond, false) { + t.Fatal("guard abandoned before reaching the limit") + } + } + if g.record(resumableLegsMinStable, false) { + t.Fatal("a stable leg must reset, not trip, the guard") + } + if g.consecutiveFast != 0 { + t.Fatalf("consecutive fast count after stable leg = %d, want 0", g.consecutiveFast) + } + + for i := 0; i < maxConsecutiveFastResumes-1; i++ { + if g.record(time.Millisecond, false) { + t.Fatalf("old fast failures leaked across reset at new failure %d", i+1) + } + } + if g.record(time.Millisecond, true) { + t.Fatal("a productive fast leg must reset, not trip, the guard") + } + if g.consecutiveFast != 0 { + t.Fatalf("consecutive fast count after productive leg = %d, want 0", g.consecutiveFast) + } +} + +// A current resumable WebSocket attachment may be interrupted merely to +// re-check its state. With no received bytes there is no ack to overwrite the +// sentinel error; this is the exact path that used to leak errPipeInterrupted +// out of wsWritePumpResumable and close an otherwise healthy connection. +func TestWebSocketServerInterruptWithoutAckKeepsCurrentAttachment(t *testing.T) { + cfg := testResumeServerConfig() + ts, st := newResumeTestServer(t, cfg, Hooks{}) + resp, cr := postConnect(t, ts, ConnectRequest{ + ProtocolVersion: ProtocolVersion, + PreferWebSocket: true, + PreferResume: true, + }) + if resp.StatusCode != http.StatusOK || !cr.Resumable { + t.Fatalf("connect = %d resumable=%v, want a resumable WebSocket", resp.StatusCode, cr.Resumable) + } + s, _ := st.Get(cr.SessionID) + ws := dialWS(t, ts, cr.SessionID) + + // Read one heartbeat so the handler is attached and its write pump has + // entered the normal pipe wait with recvOffset still zero. + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + _, msg, err := ws.Read(ctx) + cancel() + if err != nil { + t.Fatalf("initial heartbeat: %v", err) + } + if typ, _, err := wsDecode(msg); err != nil || typ != frameHeartbeat { + t.Fatalf("initial frame = (%v, %v), want heartbeat", typ, err) + } + + s.rs.interruptOut() + + ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second) + _, msg, err = ws.Read(ctx) + cancel() + if err != nil { + t.Fatalf("WebSocket closed after a harmless interrupt: %v", err) + } + if typ, _, err := wsDecode(msg); err != nil || typ != frameHeartbeat { + t.Fatalf("frame after interrupt = (%v, %v), want heartbeat", typ, err) + } +} + // --------------------------------------------------------------------------- // end to end, through a proxy that breaks // --------------------------------------------------------------------------- @@ -807,6 +893,124 @@ func isClosed(ch <-chan struct{}) bool { } } +// A level-triggered interrupt can remain pending while no ack is due. It is a +// wake-up, not a failed leg: the client write pump must keep running. Drive the +// pump directly so a heartbeat observed by the peer is an explicit readiness +// signal; because interrupts are level-triggered, injecting one after that +// point guarantees the current or next nextOut wait consumes it. +func TestWebSocketClientInterruptWithoutAckDoesNotStopWriteLoop(t *testing.T) { + serverWS := make(chan *websocket.Conn, 1) + handlerDone := make(chan struct{}) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ws, err := websocket.Accept(w, r, &websocket.AcceptOptions{InsecureSkipVerify: true}) + if err != nil { + return + } + serverWS <- ws + <-handlerDone + ws.CloseNow() + })) + t.Cleanup(func() { + close(handlerDone) + ts.Close() + }) + + clientWS, _, err := websocket.Dial(context.Background(), ts.URL, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { clientWS.CloseNow() }) + peerWS := <-serverWS + + ctx, cancel := context.WithCancel(context.Background()) + rc := &resumableConn{ + rl: newReliable(NewBufferedPipe(), NewBufferedPipe(), DefaultMaxReplayBytes), + heartbeat: 20 * time.Millisecond, + idleTimeout: time.Second, + coalesceWindow: time.Millisecond, + maxFrame: 4 << 10, + } + loopDone := make(chan error, 1) + go func() { loopDone <- rc.wsWriteLoop(ctx, clientWS) }() + t.Cleanup(func() { + cancel() + rc.rl.interruptOut() + <-loopDone + }) + + readHeartbeat := func(stage string) { + t.Helper() + rctx, cancelRead := context.WithTimeout(context.Background(), 2*time.Second) + typ, msg, err := peerWS.Read(rctx) + cancelRead() + if err != nil { + t.Fatalf("%s heartbeat: %v", stage, err) + } + if typ != websocket.MessageBinary { + t.Fatalf("%s message type = %v, want binary", stage, typ) + } + ft, payload, err := wsDecode(msg) + if err != nil || ft != frameHeartbeat || len(payload) != 0 { + t.Fatalf("%s frame = (%v, %q, %v), want empty heartbeat", stage, ft, payload, err) + } + } + + readHeartbeat("ready") + rc.rl.interruptOut() + readHeartbeat("after interrupt") +} + +// Even if an unknown transport defect survives the targeted interrupt fix, +// successful handshakes followed by immediately dead replacement legs must be +// bounded. This proxy middleware accepts and instantly closes every WebSocket +// dial after the first resume, while allowing /resume itself to keep returning +// 200, reproducing the shape of the production spin. +func TestSuperviseAbandonsConsecutiveFastSuccessfulResumes(t *testing.T) { + var poisonWebSockets atomic.Bool + middleware := func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/resume") { + poisonWebSockets.Store(true) + next.ServeHTTP(w, r) + return + } + if poisonWebSockets.Load() && r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/ws") { + ws, err := websocket.Accept(w, r, &websocket.AcceptOptions{InsecureSkipVerify: true}) + if err == nil { + ws.CloseNow() + } + return + } + next.ServeHTTP(w, r) + }) + } + + e := newResumeE2E(t, TransportWebSocket, nil, middleware) + conn, err := e.connector(nil).Connect(context.Background()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { conn.Close() }) + + waitFor(t, 2*time.Second, func() bool { return e.proxy.connCount() >= 2 }) + e.proxy.killAll() + + select { + case <-conn.TransportFailed(): + case <-time.After(10 * time.Second): + t.Fatal("supervisor kept resuming immediately dead legs instead of abandoning the session") + } + + got := int(e.resumes.Load()) + // The initial leg is normally fast and contributes to the limit. If a + // slow test machine kept it alive past the stable threshold, one extra + // successful resume is needed before five poisoned legs accumulate. + if got < maxConsecutiveFastResumes || got > maxConsecutiveFastResumes+1 { + t.Fatalf("resume handshakes before abandonment = %d, want %d or %d", + got, maxConsecutiveFastResumes, maxConsecutiveFastResumes+1) + } +} + // ★ Acceptance: the transport is killed repeatedly in the middle of a bulk // transfer, and the yamux session, the stream, and every byte survive. func TestE2EResumeSurvivesTransportKills_Stream(t *testing.T) { diff --git a/websocket.go b/websocket.go index af0725e..c3cc153 100644 --- a/websocket.go +++ b/websocket.go @@ -303,7 +303,11 @@ func wsWritePumpResumable(ctx context.Context, c *websocket.Conn, s *Session, cf if !s.att.isCurrent(att) { return errDetached } + // A current attachment was only nudged to re-check state or + // carry an ack. Do not leak that internal signal as a WebSocket + // write failure when no ack is currently due. interrupted = true + err = nil } wctx, cancel := context.WithTimeout(ctx, idle)