Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
# Cross-repo planning document, kept out of the standalone library.
DESIGN.md
plans
201 changes: 201 additions & 0 deletions atomic_idle_close_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
package pollmux

import (
"net/http"
"sync"
"testing"
"time"
)

func TestCloseSessionIfNoPollInFlight(t *testing.T) {
st := NewSessionStore()
s := newSession("idle", nil)
st.add(s)

var mu sync.Mutex
calls := 0
h := Hooks{OnDisconnect: func(got *Session, reason DisconnectReason) {
mu.Lock()
defer mu.Unlock()
if got != s || reason != ReasonServerClose {
t.Errorf("OnDisconnect(%p, %v), want (%p, %v)", got, reason, s, ReasonServerClose)
}
calls++
}}

if !CloseSessionIfNoPollInFlight(st, h, s, ReasonServerClose) {
t.Fatal("idle close returned false")
}
if !s.IsClosed() || st.Len() != 0 {
t.Fatal("idle close did not close and remove the session")
}
if CloseSessionIfNoPollInFlight(st, h, s, ReasonServerClose) {
t.Fatal("second idle close returned true")
}
mu.Lock()
defer mu.Unlock()
if calls != 1 {
t.Fatalf("OnDisconnect called %d times, want 1", calls)
}
}

func TestCloseSessionIfNoPollInFlightRejectsAttachedTransport(t *testing.T) {
st := NewSessionStore()
s := newSession("busy", nil)
st.add(s)
if !s.beginPoll() {
t.Fatal("beginPoll failed")
}

if CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) {
t.Fatal("closed a session with a poll attached")
}
if s.IsClosed() || st.Len() != 1 {
t.Fatal("failed conditional close changed the session")
}

s.endPoll()
if !CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) {
t.Fatal("close failed after poll detached")
}
}

func TestCloseSessionIfNoPollInFlightChecksStoreIdentity(t *testing.T) {
st := NewSessionStore()
old := newSession("same", nil)
current := newSession("same", nil)
st.add(current)

if CloseSessionIfNoPollInFlight(st, Hooks{}, old, ReasonServerClose) {
t.Fatal("closed a non-current session object")
}
if got, ok := st.Get("same"); !ok || got != current {
t.Fatal("store's current session was changed")
}
}

func TestCloseSessionIfNoPollInFlightRejectsWebSocketThenClosesAfterDetach(t *testing.T) {
st := NewSessionStore()
s := newSession("ws", nil)
st.add(s)
if !s.beginWebSocket() {
t.Fatal("beginWebSocket failed")
}
if CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) {
t.Fatal("closed a session with a websocket attached")
}
s.endWebSocket()
if !CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) {
t.Fatal("close failed after websocket detached")
}
}

func TestBeginPollAndConditionalCloseAreLinearizable(t *testing.T) {
for i := 0; i < 1000; i++ {
st := NewSessionStore()
s := newSession("race", nil)
st.add(s)

start := make(chan struct{})
var wg sync.WaitGroup
wg.Add(2)
var began, closed bool
go func() { defer wg.Done(); <-start; began = s.beginPoll() }()
go func() {
defer wg.Done()
<-start
closed = CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose)
}()
close(start)
wg.Wait()

if began == closed {
t.Fatalf("iteration %d: beginPoll=%v close=%v; exactly one must win", i, began, closed)
}
if began {
s.endPoll()
}
}
}

func TestConditionalCloseRacesCloseSessionExactlyOnce(t *testing.T) {
for i := 0; i < 200; i++ {
st := NewSessionStore()
s := newSession("race-close", nil)
st.add(s)
var mu sync.Mutex
calls := 0
h := Hooks{OnDisconnect: func(*Session, DisconnectReason) { mu.Lock(); calls++; mu.Unlock() }}
start := make(chan struct{})
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); <-start; CloseSession(st, h, s, ReasonServerClose) }()
go func() { defer wg.Done(); <-start; CloseSessionIfNoPollInFlight(st, h, s, ReasonEvicted) }()
close(start)
wg.Wait()
mu.Lock()
if calls != 1 {
t.Fatalf("iteration %d: OnDisconnect calls = %d, want 1", i, calls)
}
mu.Unlock()
}
}

func TestConditionalCloseRacesDeleteExactlyOnce(t *testing.T) {
var mu sync.Mutex
calls := 0
h := Hooks{OnDisconnect: func(*Session, DisconnectReason) { mu.Lock(); calls++; mu.Unlock() }}
ts, st := newTestServer(t, testServerConfig(), h)
cr := connectOK(t, ts)
s, _ := st.Get(cr.SessionID)

start := make(chan struct{})
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
<-start
req, _ := http.NewRequest(http.MethodDelete, ts.URL+"/tunnel/"+cr.SessionID, nil)
resp, err := ts.Client().Do(req)
if err == nil {
resp.Body.Close()
}
}()
go func() { defer wg.Done(); <-start; CloseSessionIfNoPollInFlight(st, h, s, ReasonEvicted) }()
close(start)
wg.Wait()
mu.Lock()
defer mu.Unlock()
if calls != 1 {
t.Fatalf("OnDisconnect calls = %d, want 1", calls)
}
}

func TestConditionalCloseRacesSweeperExactlyOnce(t *testing.T) {
st := NewSessionStore()
s := newSession("sweep-race", nil)
s.mu.Lock()
s.lastActive = time.Now().Add(-time.Hour)
s.mu.Unlock()
st.add(s)
var mu sync.Mutex
calls := 0
callback := func(*Session) { mu.Lock(); calls++; mu.Unlock() }

start := make(chan struct{})
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); <-start; st.sweep(time.Millisecond, callback) }()
go func() {
defer wg.Done()
<-start
CloseSessionIfNoPollInFlight(st, Hooks{OnDisconnect: func(*Session, DisconnectReason) { callback(s) }}, s, ReasonEvicted)
}()
close(start)
wg.Wait()
mu.Lock()
defer mu.Unlock()
if calls != 1 {
t.Fatalf("disconnect/eviction calls = %d, want 1", calls)
}
}
9 changes: 8 additions & 1 deletion client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ func (f *fakeServer) serveConnect(w http.ResponseWriter, r *http.Request) {
json.NewDecoder(r.Body).Decode(&req)
f.mu.Lock()
f.connects = append(f.connects, req)
sessionID := f.sessionID
f.mu.Unlock()

for k, v := range f.connectHeader {
Expand All @@ -131,7 +132,7 @@ func (f *fakeServer) serveConnect(w http.ResponseWriter, r *http.Request) {
}
resp := ConnectResponse{
ProtocolVersion: ProtocolVersion,
SessionID: f.sessionID,
SessionID: sessionID,
Limits: f.limits,
Meta: f.connectMeta,
}
Expand Down Expand Up @@ -578,13 +579,19 @@ func TestPoll410IgnoredWhenSessionSuperseded(t *testing.T) {
f := newFakeServer(t)
connector := f.connector()

f.mu.Lock()
f.sessionID = "sess-a"
f.mu.Unlock()
conn1 := mustConnect(t, connector)

f.mu.Lock()
f.sessionID = "sess-b"
f.mu.Unlock()
conn2 := mustConnect(t, connector)

f.mu.Lock()
f.goneSessions = map[string]struct{}{"sess-a": {}}
f.mu.Unlock()

select {
case <-conn1.SessionSuperseded():
Expand Down
40 changes: 26 additions & 14 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,11 @@ func PollHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler {
return
}

if !s.beginPoll() {
writeError(w, http.StatusGone, "session closed")
return
}
defer s.endPoll()
s.touch()

// Before the wait, not after: a callback that runs after a 30-second
Expand Down Expand Up @@ -421,12 +426,6 @@ func PollHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler {
return
}

// A parked poll is proof the client is still there, and the count
// drops the moment this handler returns — including when the TCP
// connection breaks underneath it.
s.pollInFlight.Add(1)
defer s.pollInFlight.Add(-1)

buf := make([]byte, cfg.PollBufferSize)
n, err := s.toClient.ReadAvailable(buf, cfg.PollTimeout, cfg.CoalesceWindow)

Expand Down Expand Up @@ -466,8 +465,7 @@ func pollStream(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerCo
return
}

s.pollInFlight.Add(1)
defer s.pollInFlight.Add(-1)
// PollHandler owns the lifecycle attachment for this request.

// Headers must go out now, not on the first frame. The client's
// ResponseHeaderTimeout for a stream-mode poll is short (it only needs
Expand Down Expand Up @@ -534,8 +532,7 @@ func pollStream(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerCo
// is safely between frames (see DESIGN.md's "谁来决定轮转" section). This
// handler just reads until told to stop.
func pollSendStream(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerConfig) {
s.pollInFlight.Add(1)
defer s.pollInFlight.Add(-1)
// PollHandler owns the lifecycle attachment for this request.

// A read-idle watchdog is this handler's only liveness signal: unlike
// pollStream (where the server is the writer and controls the pace
Expand Down Expand Up @@ -641,12 +638,27 @@ func CloseSession(st *SessionStore, h Hooks, s *Session, reason DisconnectReason
}

func closeSession(st *SessionStore, h Hooks, s *Session, reason DisconnectReason) {
st.Remove(s.ID)
// closeOnce is the guard: exactly one caller gets true, so a delete racing
// an eviction cannot fire OnDisconnect twice.
if s.closeOnce() && h.OnDisconnect != nil {
if !st.removeAndMarkClosed(s, false) {
return
}
s.closePipes()
if h.OnDisconnect != nil {
h.OnDisconnect(s, reason)
}
}

// CloseSessionIfNoPollInFlight atomically closes s only when it is still the
// current store entry and no poll or persistent transport is attached. It
// returns true only when this call completed the removal and close.
func CloseSessionIfNoPollInFlight(st *SessionStore, h Hooks, s *Session, reason DisconnectReason) bool {
if !st.removeAndMarkClosed(s, true) {
return false
}
s.closePipes()
if h.OnDisconnect != nil {
h.OnDisconnect(s, reason)
}
return true
}

// StartSweeper runs the store's expiry scan with this config's timings, wired
Expand Down
46 changes: 46 additions & 0 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,52 @@ func TestPollInFlightIsVisibleWhileParked(t *testing.T) {
waitFor(t, time.Second, func() bool { return s.PollInFlight() == 0 })
}

func TestConditionalCloseRejectsBatchPollThenPollsClosedSession(t *testing.T) {
ts, st := newTestServer(t, testServerConfig(), Hooks{})
cr := connectOK(t, ts)
s, _ := st.Get(cr.SessionID)

done := make(chan *http.Response, 1)
go func() { done <- poll(t, ts, cr.SessionID, nil, map[string]string{HeaderReceiveOnly: "true"}) }()
waitFor(t, time.Second, func() bool { return s.PollInFlight() == 1 })
if CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) {
t.Fatal("closed a session with a batch poll in flight")
}
resp := <-done
resp.Body.Close()
if !CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) {
t.Fatal("close failed after batch poll returned")
}
resp = poll(t, ts, cr.SessionID, nil, map[string]string{HeaderReceiveOnly: "true"})
resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("poll after close = %d, want 404", resp.StatusCode)
}
}

func TestConditionalCloseRejectsStreamPoll(t *testing.T) {
cfg := testServerConfig()
cfg.PollMode = PollModeStream
cfg.HeartbeatInterval = 20 * time.Millisecond
cfg.StreamMaxDuration = 500 * time.Millisecond
ts, st := newTestServer(t, cfg, Hooks{})
resp, cr := postConnect(t, ts, ConnectRequest{ProtocolVersion: ProtocolVersion, PreferStreamMode: true})
if resp.StatusCode != http.StatusOK || cr.PollMode != PollModeStream {
t.Fatalf("stream connect = %d mode %q", resp.StatusCode, cr.PollMode)
}
s, _ := st.Get(cr.SessionID)

done := make(chan *http.Response, 1)
go func() { done <- poll(t, ts, cr.SessionID, nil, map[string]string{HeaderReceiveOnly: "true"}) }()
waitFor(t, time.Second, func() bool { return s.PollInFlight() == 1 })
if CloseSessionIfNoPollInFlight(st, Hooks{}, s, ReasonServerClose) {
t.Fatal("closed a session with a stream poll in flight")
}
CloseSession(st, Hooks{}, s, ReasonServerClose)
got := <-done
got.Body.Close()
}

// OnPoll runs before the wait, so a health report is acted on now rather than
// a poll timeout later.
func TestOnPollRunsBeforeTheWait(t *testing.T) {
Expand Down
9 changes: 8 additions & 1 deletion relay_topology_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1170,5 +1170,12 @@ func TestStoreReflectsLiveSessionsForStatus(t *testing.T) {
}

cancel()
waitFor(t, 15*time.Second, func() bool { return b.store.Len() == 0 })
// ReconnectLoop cancellation stops transport activity, but it does not send
// DELETE: production servers remove these sessions through their normal
// shutdown/expiry path. Exercise graceful shutdown explicitly so this test
// does not depend on a 60-second sweeper timeout.
for _, s := range b.store.All() {
CloseSession(b.store, b.hooks, s, ReasonServerClose)
}
waitFor(t, 5*time.Second, func() bool { return b.store.Len() == 0 })
}
Loading
Loading