diff --git a/x/sync/network_client.go b/x/sync/network_client.go index 22d7766f3f52..37136d0a4d7c 100644 --- a/x/sync/network_client.go +++ b/x/sync/network_client.go @@ -274,23 +274,24 @@ func (c *networkClient) request( var ( response []byte + responded bool startTime = time.Now() ) - select { case <-ctx.Done(): c.peers.TrackBandwidth(nodeID, 0) return nil, ctx.Err() - case response = <-handler.responseChan: - elapsedSeconds := time.Since(startTime).Seconds() - bandwidth := float64(len(response))/elapsedSeconds + epsilon - c.peers.TrackBandwidth(nodeID, bandwidth) + case response, responded = <-handler.responseChan: } - if handler.failed { + if !responded { c.peers.TrackBandwidth(nodeID, 0) return nil, errRequestFailed } + elapsedSeconds := time.Since(startTime).Seconds() + bandwidth := float64(len(response))/elapsedSeconds + epsilon + c.peers.TrackBandwidth(nodeID, bandwidth) + c.log.Debug("received response from peer", zap.Stringer("nodeID", nodeID), zap.Uint32("requestID", requestID), diff --git a/x/sync/response_handler.go b/x/sync/response_handler.go index 624a3221fc9c..3f14e94dae4e 100644 --- a/x/sync/response_handler.go +++ b/x/sync/response_handler.go @@ -20,23 +20,22 @@ func newResponseHandler() *responseHandler { // Implements [ResponseHandler]. // Used to wait for a response after making a synchronous request. -// responseChan may contain response bytes if the original request has not failed. +// responseChan contains response bytes if the request succeeded. // responseChan is closed in either fail or success scenario. type responseHandler struct { // If [OnResponse] is called, the response bytes are sent on this channel. + // If [OnFailure] is called, the channel is closed without sending bytes. responseChan chan []byte - // Set to true in [OnFailure]. - failed bool } -// OnResponse passes the response bytes to the responseChan and closes the channel +// OnResponse passes the response bytes to the responseChan and closes the +// channel. func (h *responseHandler) OnResponse(response []byte) { h.responseChan <- response close(h.responseChan) } -// OnFailure sets the failed flag to true and closes the channel +// OnFailure closes the channel. func (h *responseHandler) OnFailure() { - h.failed = true close(h.responseChan) }