From fd52ec5db7a1bbf42cda5a7b889289e7d6afa4fe Mon Sep 17 00:00:00 2001 From: MasterCoderK <8674856+DiamondGo@users.noreply.github.com> Date: Tue, 8 Sep 2026 14:46:32 -0700 Subject: [PATCH] Fix idle WebSocket detach during resume --- resume_test.go | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++ websocket.go | 30 ++++++++++++++------ 2 files changed, 96 insertions(+), 8 deletions(-) diff --git a/resume_test.go b/resume_test.go index 93ab21e..8b30521 100644 --- a/resume_test.go +++ b/resume_test.go @@ -648,6 +648,80 @@ func TestWebSocketServerInterruptWithoutAckKeepsCurrentAttachment(t *testing.T) } } +// Resume must also be able to kick that same idle write pump off the old +// WebSocket. The kick closes the socket and interrupts nextOut; cancellation +// is what distinguishes it from the harmless interrupt covered above. Without +// that cancellation the write pump parks in nextOut again, the attachment +// never detaches, and every resume attempt receives 503. +func TestResumeKicksIdleWebSocketAttachment(t *testing.T) { + cfg := testResumeServerConfig() + // Keep the heartbeat beyond detachWait: a periodic wake-up can otherwise + // hide the stuck attachment by eventually attempting a write to the socket + // that the kick already closed. + cfg.HeartbeatInterval = 30 * time.Second + cfg.StreamMaxDuration = 2 * time.Minute + 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) + } + ws := dialWS(t, ts, cr.SessionID) + + // Send one frame as an explicit readiness signal, then leave the server + // write pump parked with neither new data nor an ack due — the exact state + // in which CloseNow alone cannot wake it. A long heartbeat keeps a periodic + // wake-up from masking the failure. + s, _ := st.Get(cr.SessionID) + if _, err := s.Write([]byte("ready")); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + _, msg, err := ws.Read(ctx) + cancel() + if err != nil { + t.Fatalf("readiness frame: %v", err) + } + if typ, _, err := wsDecode(msg); err != nil || typ != frameSeqData { + t.Fatalf("readiness frame = (%v, %v), want sequenced data", typ, err) + } + + resp, _ = postResume(t, ts, cr.SessionID, ResumeRequest{ProtocolVersion: ProtocolVersion}) + if resp.StatusCode != http.StatusOK { + t.Fatalf("resume status = %d, want 200 (old WebSocket attachment did not detach)", resp.StatusCode) + } + + // The handshake leaves the session detached; a replacement WebSocket must + // be able to claim it and become usable immediately. + replacement := dialWS(t, ts, cr.SessionID) + ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + for { + _, msg, err = replacement.Read(ctx) + if err != nil { + t.Fatalf("replacement frame: %v", err) + } + typ, payload, err := wsDecode(msg) + if err != nil { + t.Fatal(err) + } + if typ == frameAck { + continue + } + if typ != frameSeqData { + t.Fatalf("replacement frame type = %v, want ack or sequenced data", typ) + } + off, data, err := splitSeq(payload) + if err != nil || off != 0 || string(data) != "ready" { + t.Fatalf("replacement data = (offset %d, %q, %v), want (0, ready, nil)", off, data, err) + } + break + } +} + // --------------------------------------------------------------------------- // end to end, through a proxy that breaks // --------------------------------------------------------------------------- diff --git a/websocket.go b/websocket.go index c3cc153..bac1d97 100644 --- a/websocket.go +++ b/websocket.go @@ -84,11 +84,24 @@ func WebSocketHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler // is already clear for the newcomer. The kick closes the // connection (failing whichever pump is inside Read/Write) and // interrupts the write pump's pipe wait. + // Not r.Context(): coder/websocket's Accept doc warns that using the + // request context after Accept returns may lead to unexpected behavior. + // A handler-owned context instead gives attachment replacement an + // explicit way to stop both pumps without depending on socket I/O to + // notice CloseNow. It must exist before attach because kick can run as + // soon as this attachment is published. + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var att *attachment var wsRef atomic.Pointer[websocket.Conn] if s.rs != nil { var err error att, err = s.att.attach(attachBoth, func() { + // interruptOut wakes a writer parked on the outbound pipe; + // cancellation tells it this is attachment replacement, not + // the harmless ack/state nudge that it should otherwise ignore. + cancel() if c := wsRef.Load(); c != nil { c.CloseNow() } @@ -137,14 +150,6 @@ func WebSocketHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler s.rs.resetAck() } - // Not r.Context(): coder/websocket's Accept doc warns that using the - // request context after Accept returns "may lead to unexpected - // behavior" (it has hijacked the connection out from under net/http - // by that point). The pumps below need no signal from it anyway — - // clean shutdown already arrives through s.toClient/s.toServer - // closing (see closeSession), and an abrupt disconnect already - // surfaces as a Read/Write error on c itself. - ctx := context.Background() idle := cfg.HeartbeatInterval + defaultStreamReadGrace // wg tracks both pumps to completion; readErrCh/writeErrCh exist only @@ -167,6 +172,12 @@ func WebSocketHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler case firstErr = <-readErrCh: case firstErr = <-writeErrCh: } + cancel() + // A resumable writer may be parked in nextOut, which has no context + // to observe. Wake it so cancellation can make it return promptly. + if s.rs != nil { + s.rs.interruptOut() + } if errors.Is(firstErr, io.EOF) { // wsWritePump's io.EOF: the session ended server-side (delete, @@ -300,6 +311,9 @@ func wsWritePumpResumable(ctx context.Context, c *websocket.Conn, s *Session, cf case errors.Is(err, io.EOF): return io.EOF case errors.Is(err, errPipeInterrupted): + if ctx.Err() != nil { + return ctx.Err() + } if !s.att.isCurrent(att) { return errDetached }