2022-05-30 23:14:07 +02:00
|
|
|
package bytecounter
|
|
|
|
|
|
|
|
//
|
|
|
|
// model.Dialer wrappers
|
|
|
|
//
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net"
|
|
|
|
|
|
|
|
"github.com/ooni/probe-cli/v3/internal/model"
|
|
|
|
)
|
|
|
|
|
2022-06-05 21:22:27 +02:00
|
|
|
// MaybeWrapWithContextAwareDialer wraps the given dialer with a ContextAwareDialer
|
|
|
|
// if the enabled argument is true and otherwise just returns the given dialer.
|
2022-05-30 23:14:07 +02:00
|
|
|
//
|
|
|
|
// Bug
|
|
|
|
//
|
|
|
|
// This implementation cannot properly account for the bytes that are sent by
|
|
|
|
// persistent connections, because they stick to the counters set when the
|
|
|
|
// connection was established. This typically means we miss the bytes sent and
|
|
|
|
// received when submitting a measurement. Such bytes are specifically not
|
|
|
|
// seen by the experiment specific byte counter.
|
|
|
|
//
|
|
|
|
// For this reason, this implementation may be heavily changed/removed
|
|
|
|
// in the future (<- this message is now ~two years old, though).
|
2022-06-05 21:22:27 +02:00
|
|
|
func MaybeWrapWithContextAwareDialer(enabled bool, dialer model.Dialer) model.Dialer {
|
|
|
|
if !enabled {
|
|
|
|
return dialer
|
|
|
|
}
|
|
|
|
return WrapWithContextAwareDialer(dialer)
|
|
|
|
}
|
|
|
|
|
|
|
|
// contextAwareDialer is a model.Dialer that attempts to count bytes using
|
|
|
|
// the MaybeWrapWithContextByteCounters function.
|
|
|
|
type contextAwareDialer struct {
|
2022-05-30 23:14:07 +02:00
|
|
|
Dialer model.Dialer
|
|
|
|
}
|
|
|
|
|
2022-06-05 21:22:27 +02:00
|
|
|
// WrapWithContextAwareDialer creates a new ContextAwareDialer. See the docs
|
|
|
|
// of MaybeWrapWithContextAwareDialer for a list of caveats.
|
|
|
|
func WrapWithContextAwareDialer(dialer model.Dialer) *contextAwareDialer {
|
|
|
|
return &contextAwareDialer{Dialer: dialer}
|
2022-05-30 23:14:07 +02:00
|
|
|
}
|
|
|
|
|
2022-06-05 21:22:27 +02:00
|
|
|
var _ model.Dialer = &contextAwareDialer{}
|
2022-05-30 23:14:07 +02:00
|
|
|
|
|
|
|
// DialContext implements Dialer.DialContext
|
2022-06-05 21:22:27 +02:00
|
|
|
func (d *contextAwareDialer) DialContext(
|
2022-05-30 23:14:07 +02:00
|
|
|
ctx context.Context, network, address string) (net.Conn, error) {
|
|
|
|
conn, err := d.Dialer.DialContext(ctx, network, address)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
conn = MaybeWrapWithContextByteCounters(ctx, conn)
|
|
|
|
return conn, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// CloseIdleConnections implements Dialer.CloseIdleConnections.
|
2022-06-05 21:22:27 +02:00
|
|
|
func (d *contextAwareDialer) CloseIdleConnections() {
|
2022-05-30 23:14:07 +02:00
|
|
|
d.Dialer.CloseIdleConnections()
|
|
|
|
}
|