fix(all): introduce and use iox.ReadAllContext (#379)
* fix(all): introduce and use iox.ReadAllContext This improvement over the ioutil.ReadAll utility returns early if the context expires. This enables us to unblock stuck code in case there's censorship confounding the TCP stack. See https://github.com/ooni/probe/issues/1417. Compared to the functionality postulated in the above mentioned issue, I choose to be more generic and separate limiting the maximum body size (not implemented here) from using the context to return early when reading a body (or any other reader). After implementing iox.ReadAllContext, I made sure we always use it everywhere in the tree instead of ioutil.ReadAll. This includes many parts of the codebase where in theory we don't need iox.ReadAllContext. Though, changing all the places makes checking whether we're not using ioutil.ReadAll where we should not be using it easy: `git grep` should return no lines. * Update internal/iox/iox_test.go * fix(ndt7): treat context errors as non-errors The rationale is explained by the comment documenting reduceErr. * Update internal/engine/experiment/ndt7/download.go
This commit is contained in:
@@ -16,7 +16,7 @@ type collectDeps interface {
|
||||
JSONMarshal(v interface{}) ([]byte, error)
|
||||
Logger() model.Logger
|
||||
NewHTTPRequest(method string, url string, body io.Reader) (*http.Request, error)
|
||||
ReadAll(r io.Reader) ([]byte, error)
|
||||
ReadAllContext(ctx context.Context, r io.Reader) ([]byte, error)
|
||||
Scheme() string
|
||||
UserAgent() string
|
||||
}
|
||||
@@ -47,7 +47,7 @@ func collect(ctx context.Context, fqdn, authorization string,
|
||||
return errHTTPRequestFailed
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err = deps.ReadAll(resp.Body)
|
||||
data, err = deps.ReadAllContext(ctx, resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"time"
|
||||
@@ -20,6 +19,7 @@ import (
|
||||
"github.com/ooni/probe-cli/v3/internal/engine/netx/errorx"
|
||||
"github.com/ooni/probe-cli/v3/internal/engine/netx/trace"
|
||||
"github.com/ooni/probe-cli/v3/internal/humanize"
|
||||
"github.com/ooni/probe-cli/v3/internal/iox"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -86,8 +86,8 @@ func (r runner) NewHTTPRequest(meth, url string, body io.Reader) (*http.Request,
|
||||
return http.NewRequest(meth, url, body)
|
||||
}
|
||||
|
||||
func (r runner) ReadAll(reader io.Reader) ([]byte, error) {
|
||||
return ioutil.ReadAll(reader)
|
||||
func (r runner) ReadAllContext(ctx context.Context, reader io.Reader) ([]byte, error) {
|
||||
return iox.ReadAllContext(ctx, reader)
|
||||
}
|
||||
|
||||
func (r runner) Scheme() string {
|
||||
@@ -179,7 +179,7 @@ func (r runner) measure(
|
||||
current.ConnectTime = connectTime
|
||||
r.tk.ReceiverData = append(r.tk.ReceiverData, current)
|
||||
total += current.Received
|
||||
avgspeed := 8 * float64(total) / time.Now().Sub(begin).Seconds()
|
||||
avgspeed := 8 * float64(total) / time.Since(begin).Seconds()
|
||||
percentage := float64(current.Iteration) / float64(numIterations)
|
||||
message := fmt.Sprintf("streaming: speed: %s", humanize.SI(avgspeed, "bit/s"))
|
||||
r.callbacks.OnProgress(percentage, message)
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
type downloadDeps interface {
|
||||
HTTPClient() *http.Client
|
||||
NewHTTPRequest(method string, url string, body io.Reader) (*http.Request, error)
|
||||
ReadAll(r io.Reader) ([]byte, error)
|
||||
ReadAllContext(ctx context.Context, r io.Reader) ([]byte, error)
|
||||
Scheme() string
|
||||
UserAgent() string
|
||||
}
|
||||
@@ -57,7 +57,7 @@ func download(ctx context.Context, config downloadConfig) (downloadResult, error
|
||||
return result, errHTTPRequestFailed
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := config.deps.ReadAll(resp.Body)
|
||||
data, err := config.deps.ReadAllContext(ctx, resp.Body)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
@@ -66,7 +66,7 @@ func download(ctx context.Context, config downloadConfig) (downloadResult, error
|
||||
// turns out that Neubot and MK do the same. So, we do what they do. At
|
||||
// the same time, we are currently not able to include the overhead that
|
||||
// is caused by HTTP headers etc. So, we're a bit less precise.
|
||||
result.elapsed = time.Now().Sub(savedTicks).Seconds()
|
||||
result.elapsed = time.Since(savedTicks).Seconds()
|
||||
result.received = int64(len(data))
|
||||
result.requestTicks = savedTicks.Sub(config.begin).Seconds()
|
||||
result.timestamp = time.Now().Unix()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package dash
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
@@ -36,7 +37,7 @@ func (d FakeDeps) NewHTTPRequest(
|
||||
return d.newHTTPRequestResult, d.newHTTPRequestErr
|
||||
}
|
||||
|
||||
func (d FakeDeps) ReadAll(r io.Reader) ([]byte, error) {
|
||||
func (d FakeDeps) ReadAllContext(ctx context.Context, r io.Reader) ([]byte, error) {
|
||||
return d.readAllResult, d.readAllErr
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ type negotiateDeps interface {
|
||||
JSONMarshal(v interface{}) ([]byte, error)
|
||||
Logger() model.Logger
|
||||
NewHTTPRequest(method string, url string, body io.Reader) (*http.Request, error)
|
||||
ReadAll(r io.Reader) ([]byte, error)
|
||||
ReadAllContext(ctx context.Context, r io.Reader) ([]byte, error)
|
||||
Scheme() string
|
||||
UserAgent() string
|
||||
}
|
||||
@@ -48,7 +48,7 @@ func negotiate(
|
||||
return negotiateResp, errHTTPRequestFailed
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err = deps.ReadAll(resp.Body)
|
||||
data, err = deps.ReadAllContext(ctx, resp.Body)
|
||||
if err != nil {
|
||||
return negotiateResp, err
|
||||
}
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
package dash
|
||||
|
||||
const (
|
||||
// currentServerSchemaVersion is the version of the server schema that
|
||||
// will be adopted by this implementation. Version 3 is the one that is
|
||||
// Neubot uses. We needed to bump the version because Web100 is not on
|
||||
// M-Lab anymore and hence we need to make a breaking change.
|
||||
currentServerSchemaVersion = 4
|
||||
|
||||
// negotiatePath is the URL path used to negotiate
|
||||
negotiatePath = "/negotiate/dash"
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@ package hhfm_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/ooni/probe-cli/v3/internal/iox"
|
||||
)
|
||||
|
||||
type FakeDialer struct {
|
||||
@@ -30,7 +31,7 @@ func (txp FakeTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
return txp.Func(req)
|
||||
}
|
||||
if req.Body != nil {
|
||||
ioutil.ReadAll(req.Body)
|
||||
iox.ReadAllContext(req.Context(), req.Body)
|
||||
req.Body.Close()
|
||||
}
|
||||
if txp.Err != nil {
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"sort"
|
||||
@@ -21,6 +20,7 @@ import (
|
||||
"github.com/ooni/probe-cli/v3/internal/engine/netx/archival"
|
||||
"github.com/ooni/probe-cli/v3/internal/engine/netx/dialer"
|
||||
"github.com/ooni/probe-cli/v3/internal/engine/netx/errorx"
|
||||
"github.com/ooni/probe-cli/v3/internal/iox"
|
||||
"github.com/ooni/probe-cli/v3/internal/randx"
|
||||
)
|
||||
|
||||
@@ -198,7 +198,7 @@ func transact(txp Transport, req *http.Request,
|
||||
return nil, nil, urlgetter.ErrHTTPRequestFailed
|
||||
}
|
||||
callbacks.OnProgress(0.75, "reading response body...")
|
||||
data, err := ioutil.ReadAll(resp.Body)
|
||||
data, err := iox.ReadAllContext(req.Context(), resp.Body)
|
||||
callbacks.OnProgress(1.00, fmt.Sprintf("got reseponse body... %+v", err))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
|
||||
@@ -2,11 +2,12 @@ package ndt7
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/ooni/probe-cli/v3/internal/iox"
|
||||
)
|
||||
|
||||
type downloadManager struct {
|
||||
@@ -33,6 +34,30 @@ func newDownloadManager(
|
||||
}
|
||||
|
||||
func (mgr downloadManager) run(ctx context.Context) error {
|
||||
return mgr.reduceErr(mgr.doRun(ctx))
|
||||
}
|
||||
|
||||
// reduceErr treats as non-errors the errors caused by the context
|
||||
// so that we can focus instead on network errors.
|
||||
//
|
||||
// This function was introduced by https://github.com/ooni/probe-cli/pull/379
|
||||
// since before such a PR we did not see context interrupting
|
||||
// errors when we were reading messages. Since before such a PR
|
||||
// we used to return `nil` on context errors, this function is
|
||||
// here to keep the previous behavior by filtering the error
|
||||
// returned when reading messages, given that now reading messages
|
||||
// can fail midway because we use iox.ReadAllContext.
|
||||
func (mgr downloadManager) reduceErr(err error) error {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (mgr downloadManager) doRun(ctx context.Context) error {
|
||||
var total int64
|
||||
start := time.Now()
|
||||
if err := mgr.conn.SetReadDeadline(start.Add(mgr.maxRuntime)); err != nil {
|
||||
@@ -47,7 +72,7 @@ func (mgr downloadManager) run(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
if kind == websocket.TextMessage {
|
||||
data, err := ioutil.ReadAll(reader)
|
||||
data, err := iox.ReadAllContext(ctx, reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -57,7 +82,7 @@ func (mgr downloadManager) run(ctx context.Context) error {
|
||||
}
|
||||
continue
|
||||
}
|
||||
n, err := io.Copy(ioutil.Discard, reader)
|
||||
n, err := io.Copy(io.Discard, reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -143,3 +143,20 @@ type goodJSONReader struct{}
|
||||
func (r *goodJSONReader) Read(p []byte) (int, error) {
|
||||
return copy(p, []byte(`{}`)), io.EOF
|
||||
}
|
||||
|
||||
func TestDownloadReduceErr(t *testing.T) {
|
||||
mgr := downloadManager{}
|
||||
if mgr.reduceErr(context.Canceled) != nil {
|
||||
t.Fatal("reduceErr not working as intended for context.Canceled")
|
||||
}
|
||||
if mgr.reduceErr(context.DeadlineExceeded) != nil {
|
||||
t.Fatal("reduceErr not working as intended for context.DeadlineExceeded")
|
||||
}
|
||||
if mgr.reduceErr(nil) != nil {
|
||||
t.Fatal("reduceErr not working as intended for nil")
|
||||
}
|
||||
expected := errors.New("mocked error")
|
||||
if mgr.reduceErr(expected) != expected {
|
||||
t.Fatal("reduceErr not working as intended for other errors")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user