Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: obey new stream timeout #1029

Merged
merged 1 commit into from
Dec 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions p2p/host/basic/basic_host.go
Original file line number Diff line number Diff line change
Expand Up @@ -631,10 +631,24 @@ func (h *BasicHost) NewStream(ctx context.Context, p peer.ID, pids ...protocol.I
}, nil
}

selected, err := msmux.SelectOneOf(pidStrings, s)
if err != nil {
// Negotiate the protocol in the background, obeying the context.
var selected string
errCh := make(chan error, 1)
go func() {
selected, err = msmux.SelectOneOf(pidStrings, s)
errCh <- err
}()
select {
case err = <-errCh:
if err != nil {
s.Reset()
return nil, err
}
case <-ctx.Done():
s.Reset()
return nil, err
// wait for the negotiation to cancel.
<-errCh
return nil, ctx.Err()
}

selpid := protocol.ID(selected)
Expand Down
44 changes: 44 additions & 0 deletions p2p/host/basic/basic_host_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package basichost
import (
"bytes"
"context"
"fmt"
"io"
"reflect"
"sync"
Expand Down Expand Up @@ -777,6 +778,49 @@ func TestHostAddrChangeDetection(t *testing.T) {
}
}

func TestNegotiationCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

h1, h2 := getHostPair(ctx, t)
defer h1.Close()
defer h2.Close()

// pre-negotiation so we can make the negotiation hang.
h1.Network().SetStreamHandler(func(s network.Stream) {
<-ctx.Done() // wait till the test is done.
s.Reset()
})

ctx2, cancel2 := context.WithCancel(ctx)
defer cancel2()

errCh := make(chan error, 1)
go func() {
s, err := h2.NewStream(ctx2, h1.ID(), "/testing")
if s != nil {
errCh <- fmt.Errorf("expected to fail negotiation")
return
}
errCh <- err
}()
select {
case err := <-errCh:
t.Fatal(err)
case <-time.After(10 * time.Millisecond):
// ok, hung.
}
cancel2()

select {
case err := <-errCh:
require.Equal(t, err, context.Canceled)
case <-time.After(500 * time.Millisecond):
// failed to cancel
t.Fatal("expected negotiation to be canceled")
}
}

func waitForAddrChangeEvent(ctx context.Context, sub event.Subscription, t *testing.T) event.EvtLocalAddressesUpdated {
for {
select {
Expand Down