Skip to content

Commit

Permalink
respect contexts while reading messages in dht
Browse files Browse the repository at this point in the history
License: MIT
Signed-off-by: Jeromy <[email protected]>
  • Loading branch information
whyrusleeping committed Jun 8, 2016
1 parent 0e81124 commit b3503e0
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion routing/dht/dht_net.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dht

import (
"fmt"
"sync"
"time"

Expand Down Expand Up @@ -214,7 +215,7 @@ func (ms *messageSender) SendRequest(ctx context.Context, pmes *pb.Message) (*pb
log.Event(ctx, "dhtSentMessage", ms.dht.self, ms.p, pmes)

mes := new(pb.Message)
if err := ms.r.ReadMsg(mes); err != nil {
if err := ms.ctxReadMsg(ctx, mes); err != nil {
ms.s.Close()
ms.s = nil
return nil, err
Expand All @@ -227,3 +228,23 @@ func (ms *messageSender) SendRequest(ctx context.Context, pmes *pb.Message) (*pb

return mes, nil
}

func (ms *messageSender) ctxReadMsg(ctx context.Context, mes *pb.Message) error {
t := time.NewTimer(time.Second * 30)
defer t.Stop()

errc := make(chan error, 1)
go func() {
errc <- ms.r.ReadMsg(mes)
}()

select {
case err := <-errc:
return err
case <-ctx.Done():
return ctx.Err()
case <-t.C:
log.Warning("dht context read timeout")
return fmt.Errorf("reading message timed out")
}
}

0 comments on commit b3503e0

Please sign in to comment.