Skip to content

Commit

Permalink
Restart PipelineClient worker on error (#834)
Browse files Browse the repository at this point in the history
  • Loading branch information
erikdubbelboer authored Jun 16, 2020
1 parent 380f00b commit 9dd7979
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 12 deletions.
32 changes: 20 additions & 12 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2389,20 +2389,28 @@ func (c *pipelineConnClient) init() {
c.chW = make(chan *pipelineWork, maxPendingRequests)
}
go func() {
if err := c.worker(); err != nil {
c.logger().Printf("error in PipelineClient(%q): %s", c.Addr, err)
if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
// Throttle client reconnections on temporary errors
time.Sleep(time.Second)
// Keep restarting the worker if it fails (connection errors for example).
for {
if err := c.worker(); err != nil {
c.logger().Printf("error in PipelineClient(%q): %s", c.Addr, err)
if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
// Throttle client reconnections on temporary errors
time.Sleep(time.Second)
}
} else {
c.chLock.Lock()
stop := len(c.chR) == 0 && len(c.chW) == 0
if !stop {
c.chR = nil
c.chW = nil
}
c.chLock.Unlock()

if stop {
break
}
}
}

c.chLock.Lock()
// Do not reset c.chW to nil, since it may contain
// pending requests, which could be served on the next
// connection to the host.
c.chR = nil
c.chLock.Unlock()
}()
}
c.chLock.Unlock()
Expand Down
54 changes: 54 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,60 @@ import (
"github.com/valyala/fasthttp/fasthttputil"
)

func TestPipelineClientIssue832(t *testing.T) {
t.Parallel()

ln := fasthttputil.NewInmemoryListener()

req := AcquireRequest()
defer ReleaseRequest(req)
req.SetHost("example.com")

res := AcquireResponse()
defer ReleaseResponse(res)

client := PipelineClient{
Dial: func(addr string) (net.Conn, error) {
return ln.Dial()
},
ReadTimeout: time.Millisecond * 10,
Logger: &testLogger{}, // Ignore log output.
}

attempts := 10
go func() {
for i := 0; i < attempts; i++ {
c, err := ln.Accept()
if err != nil {
t.Error(err)
}
if c != nil {
go func() {
time.Sleep(time.Millisecond * 50)
c.Close()
}()
}
}
}()

done := make(chan int)
go func() {
defer close(done)

for i := 0; i < attempts; i++ {
if err := client.Do(req, res); err == nil {
t.Error("error expected")
}
}
}()

select {
case <-time.After(time.Second):
t.Fatal("PipelineClient did not restart worker")
case <-done:
}
}

func TestClientInvalidURI(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 9dd7979

Please sign in to comment.