From 3c94741ed9327663660c31f8541faf75417864cf Mon Sep 17 00:00:00 2001 From: Johan Lindh Date: Wed, 25 Oct 2023 12:21:48 +0200 Subject: [PATCH] cancel Requests when they time out --- jaws.go | 1 + jaws_test.go | 19 +++++++++++++------ request.go | 4 +++- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/jaws.go b/jaws.go index 137a3b2..5525506 100644 --- a/jaws.go +++ b/jaws.go @@ -568,6 +568,7 @@ func (jw *Jaws) maintenance(requestTimeout time.Duration) { deadline := now.Add(-requestTimeout) for _, rq := range jw.pending { if err := jw.Log(maybeErrPendingCancelled(rq, deadline)); err != nil { + rq.cancel(err) killReqs = append(killReqs, rq) } } diff --git a/jaws_test.go b/jaws_test.go index 67a17e1..7dc689b 100644 --- a/jaws_test.go +++ b/jaws_test.go @@ -316,10 +316,14 @@ func TestJaws_CleansUpUnconnected(t *testing.T) { func TestJaws_UnconnectedLivesUntilDeadline(t *testing.T) { is := testHelper{t} + tmr := time.NewTimer(testTimeout) + defer tmr.Stop() jw := New() defer jw.Close() + hr := httptest.NewRequest(http.MethodGet, "/", nil) - rq1ctx := jw.NewRequest(hr).Context() + rq1 := jw.NewRequest(hr) + rq1ctx := rq1.Context() rq2 := jw.NewRequest(hr) rq2.Created = time.Now().Add(-time.Second * 10) rq2ctx := rq2.Context() @@ -328,13 +332,12 @@ func TestJaws_UnconnectedLivesUntilDeadline(t *testing.T) { go jw.ServeWithTimeout(time.Second) - tmr := time.NewTimer(testTimeout) for jw.Pending() > 1 { select { case <-tmr.C: - is.Fail() + is.Fatal("timeout") case <-jw.Done(): - is.Fail() + is.Error("unexpected close") default: time.Sleep(time.Millisecond) } @@ -345,12 +348,16 @@ func TestJaws_UnconnectedLivesUntilDeadline(t *testing.T) { jw.Close() select { case <-tmr.C: - is.Fail() + is.Fatal("timeout") case <-jw.Done(): } is.NoErr(context.Cause(rq1ctx)) - is.NoErr(context.Cause(rq2ctx)) + is.True(errors.Is(context.Cause(rq2ctx), ErrNoWebSocketRequest{})) + + // neither should have been recycled + is.Equal(rq1.Jaws, jw) + is.Equal(rq2.Jaws, jw) } func TestJaws_BroadcastsCallable(t *testing.T) { diff --git a/request.go b/request.go index e5de46e..bffe14b 100644 --- a/request.go +++ b/request.go @@ -199,7 +199,9 @@ func (rq *Request) cancel(err error) { rq.mu.RLock() cancelFn := rq.cancelFn rq.mu.RUnlock() - cancelFn(err) + if cancelFn != nil { + cancelFn(err) + } } }