Skip to content

Commit

Permalink
cancel Requests when they time out
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdata committed Oct 25, 2023
1 parent 638619c commit 3c94741
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
1 change: 1 addition & 0 deletions jaws.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down
19 changes: 13 additions & 6 deletions jaws_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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)
}
Expand All @@ -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) {
Expand Down
4 changes: 3 additions & 1 deletion request.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

Expand Down

0 comments on commit 3c94741

Please sign in to comment.